【问题标题】:Scan through txt file, translate certain words found in dictionary [Python]扫描txt文件,翻译字典中的某些单词[Python]
【发布时间】:2023-03-20 15:05:01
【问题描述】:

我有一个包含以下内容的文件:

((S000383212:0.0,JC0:0.244562):0.142727,(S002923086:0.0,(JC1:0.0,JC2:0.0):0.19717200000000001):0.222151,((S000594619:0.0,JC3:0.21869):0.13418400000000003,(S000964423:0.122312,JC4:0.084707):0.18147100000000002):0.011521999999999977); 

我有两个字典,其中包含:

org = {'JC4': 'a','JC0': 'b','JC1': 'c','JC2': 'c','JC3': 'd'}

RDP = {'S000383212': 'hello', 'S002923086': 'this', 'S000594619': 'is'}

每次它说出一本词典中的一个词并将其转换为替代词时,我如何找到它?

即如果遇到 'JC0' 则将其转换为 'b'

【问题讨论】:

    标签: python file dictionary word translate


    【解决方案1】:
    for key in org.keys() + RDP.keys():
        text = text.replace(key, org.get(key, None) or RDP.get(key, None))
    

    当然,正如 TryPyPy 所说,如果你只是合并 dicts,它会变得简单得多:

    org.update(RDP)
    for item in org.items():
        text = text.replace(*item)
    

    【讨论】:

    • 如果你创建一个 dict 合并 org 和 RDP,获取值变得更简单。
    【解决方案2】:

    如果性能不是很重要,可以使用以下代码:

    with open('your_file_name.txt') as f:
        text = f.read()
        for key, value in org.items() + RDP.items():
            text = text.replace(key, value)
    

    此代码的时间复杂度为O(n * k),其中ntext 的长度,k 是两个字典中的条目数。如果这种复杂性不适合您的任务,Aho-Corasick algorithm 可以帮助您。

    【讨论】:

    • 您应该将第一行替换为 with... open(): 或将 openread 分配分开。如果没有 with 或显式 close(),则无法保证文件关闭。
    【解决方案3】:

    您应该使用replace 字符串方法。

    【讨论】:

      猜你喜欢
      • 2012-05-29
      • 2011-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      相关资源
      最近更新 更多