如何在未知传入格式的字符串中随机分配数字?

如何解决如何在未知传入格式的字符串中随机分配数字?

对于NLP项目,我需要根据训练示例生成随机数字符串以用于训练。数字以字符串形式出现(来自OCR)。让我在这里将问题陈述限制为百分比值,到目前为止,观察到的格式包括以下格式或指出格式功能的任何有意义的组合:

'60'       # no percentage sign,precision 0,no other characters
'60.00'    # no percentage sign,precision 2,dot for digit separation
'60,000'   # no percentage sign,precision 3,comma for digit separation
'60.0000'  # no percentage sign,precision 4,dot for digit separation
'60.00%'   # same as above,with percentage sign
'60.00 %'  # same as above,with whitespace
'100%'     # three digits,zero precision,percentage sign
'5'        # single digit
'% 60'     # percentage sign in front of the number,whitespace

我的目标是在保留每个字符格式的同时将数字随机化(例外:由于将5.6随机化为18.7或100.0时数字位数不同,反之亦然)。百分比值的值应介于0到100之间。我需要一些示例:

input  = '5'  # integer-like digit
output = [  '7','18','100'] 

input  =  '100.00 %' # 2-precision float with whitespace & percentage sign
output = [  '5.38 %','38.05 %','100.00 %']  

inpput =  '% 60,000' # percentage sign,whitespace,4-precision float,comma separator
output = ['% 5,5348','% 48,7849','% 100,0000'] 

我该怎么做?解决方案可以是概念性代码示例。 解决方案需要反映出可能出现在实际数据中的格式

到目前为止,我所知道的最好的办法是针对我能想到的每种格式变体强行手写if子句。

解决方法

以下内容似乎适用于您提供的示例输入。我们只想查找前导整数和可能的分隔符,然后再输入更多的数字。实际上,我们实际上不需要查找任何空格或百分号,因为无论如何,我们仅对替换任何给定匹配项中的数字感兴趣。让我知道是否错过了一些事情:

import re

pattern = "\\d{1,3}((?P<separator>[,.])(?P<floating>\\d+))?"

strings = (
    "60","60.00","60,000","60.0000","60.00%","60.00 %","100%","5","% 60","% 60,000"
)

def randomize(match):
    from random import uniform

    integer,floating = divmod(uniform(0,100),1)

    def get_chars():
        yield str(int(integer))
        if match.group("separator") is not None:
            yield match.group("separator")
            precision = len(match.group("floating"))
            yield f"{{:.{precision}f}}".format(floating)[2:]
    return "".join(get_chars())
        
    

for string in strings:
    print(re.sub(pattern,randomize,string))

输出:

29
95.08
51,507
9.1783
0.80%
6.56 %
16%
22
% 27
% 93,174
>>> 
,

可以调用以下函数来生成您所需要的随机数。您可以对其进行进一步修改,以使其最适合您的情况。

import numpy as np
def random_gen():
    precison = np.random.randint(0,6)
    val = np.random.uniform(0,100)
    val = round(val,int(precison))
    val = str(val)
    
    white_space = np.random.randint(0,3)
    rand_index = np.random.randint(0,len(val))
    val = val[0:rand_index] + ' '*white_space + val[rand_index:]
    
    if np.random.randint(0,2) > 0:
        if np.random.randint(0,2) > 0:
            val = val + "%"
        else:
            val = "%" + val
    return val

random_gen()      

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-