如何解决如何在未知传入格式的字符串中随机分配数字?
对于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 举报,一经查实,本站将立刻删除。