【问题标题】:How to parse all the coefficients of a polynomial string in python如何在python中解析多项式字符串的所有系数
【发布时间】:2020-07-04 09:51:37
【问题描述】:

我有一个 .txt 文件,其中包含以字符串形式存储的大量多项式。一个有代表性的例子如下。 6*n101110111*n111111111 + 3*n101111101 + 6*n101111111 + n111111111 但一般来说,多项式由“n + str(所有可能的长度为 9 的二进制数字)”以不同的顺序乘以系数组成。术语和“+”的数量事先不知道。 结果应该是,

[6,3,6,1]

如果能把它当成字典就更好了

{ n101110111*n111111111: 6, n101111101: 3, n101111111: 6, n111111111 :1}

【问题讨论】:

  • 您显示的字符串是否构成文件中的典型行?如果是这样,文件的每一行都是感兴趣的吗?6*n101110111*n111111111 部分是否总是在行的开头?此示例有四个用加号分隔的术语。所有感兴趣的字符串都恰好有四个术语吗?如果不是,最大的术语数是多少?一些加号可以是减号吗?请通过编辑您的问题而不是在评论中提供此信息。

标签: python regex string parsing


【解决方案1】:

((\d)?\*?((?:n\d+)(?:\*n\d+)*))(Regex demo) 这样的正则表达式就可以完成这项工作

line = "6*n101110111*n111111111 + 3*n101111101 + 6*n101111111 + n111111111"
res = {}

matches = re.findall(r"(?:(\d)?\*?((?:n\d+)(?:\*n\d+)*))", line)
print(matches)  # [('6', 'n101110111*n111111111'), ('3', 'n101111101'), ('6', 'n101111111'), ('', 'n111111111')]

for match in matches:
    res[match[1]] = match[0] or 1
print(res)  # {'n101110111*n111111111': '6', 'n101111101': '3', 
               'n101111111': '6', 'n111111111': 1}

【讨论】:

    【解决方案2】:

    我想我有一个适合你的解决方案:

    
    stringList = yourStringHere.split("+")
    outputDict = {}
    
    for sub in stringList:
        values = sub.split("*")
        try:
            baseNum = int(values[0])
            poly = "*".join(values[1:]).strip()
        except:
            baseNum = 1
            poly = "*".join(values).strip()
        outputDict[poly] = baseNum 
    

    这种方法的唯一缺点是字典包含唯一键,因此如果您的字典中有其他类似的权限,它们将被覆盖。

    【讨论】:

    • 我喜欢这个解决方案的简洁性,但是你的解决方案不会解析 'n111111111 :1'
    【解决方案3】:

    你可以使用:

    import re
    
    s = '6*n101110111*n111111111 + 3*n101111101 + 6*n101111111 + n111111111'
    
    l = [g.group().split('*', 1)  for g in re.finditer(r'\b([\dn*]+)\b', s)]
    {e[-1]: 1 if len(e) == 1 else int(e[0]) for e in l}
    

    输出:

    {'n101110111*n111111111': 6,
     'n101111101': 3,
     'n101111111': 6,
     'n111111111': 1}
    

    【讨论】:

    • 您可以将您的角色类别缩短为[*n\d]。不过,不错的pythoning。 ^^
    【解决方案4】:

    你可以使用正则表达式

    r" (?:(\d+)\*)?([^ +-]+)
    

    Python demo

    正则表达式引擎对每个匹配项执行以下操作:

    (?:        # begin a non-capture group
      (\d+)    # match 1+ digits in capture group 1
      \*       # match '*'
    )          # end non-capture group
    ?          # optionally match non-capture group
    ([^ +-]+)  # match 1+ chars other than spaces, '+', and '-' in
               # capture group 2
    

    【讨论】:

    • 我不熟悉 Python,但是从捕获组的内容创建哈希应该很简单,类似于 Ruby 代码str.gsub(r).with_object({}) {|_,h| h[$2] = ($1 || 1).to_i} #=> {"n101110111*n111111111"=>6, "n101111101"=>3, "n101111111"=>6, "n111111111"=>1},其中r 是正则表达式。
    猜你喜欢
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多