为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕侠2389804 2023-05-23 10:51:17
对于 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 digitoutput = [  '7',            '18',           '100'] input  =  '100.00 %' # 2-precision float with whitespace & percentage signoutput = [  '5.38 %',            '38.05 %',           '100.00 %']  inpput =  '% 60,000' # percentage sign, whitespace, 4-precision float, comma separatoroutput = ['% 5,5348',           '% 48,7849',           '% 100,0000'] 我怎么能这样做?解决方案可以是概念性的,也可以是代码示例。解决方案需要反映真实数据中可能出现的格式到目前为止,我所知道的最好的方法是为我能想到的每种格式变体强制手写 if 子句。
查看完整描述

2 回答

?
胡子哥哥

TA贡献1825条经验 获得超6个赞

以下内容似乎适用于您提供的示例输入。我们只对找到前导整数数字和后面跟有更多数字的潜在分隔符感兴趣。我们实际上不需要寻找任何空格或百分号,因为无论如何我们只对替换任何给定匹配项中的数字感兴趣。如果我错过了什么,请告诉我:


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

>>> 


查看完整回答
反对 回复 2023-05-23
?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

可以调用以下函数来生成您的情况所需的随机数。您可以进一步修改它以最适合您的情况。


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()      


查看完整回答
反对 回复 2023-05-23
  • 2 回答
  • 0 关注
  • 104 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信