【问题标题】:Replacing exact numbers with words from DICT python用 DICT python 中的单词替换确切的数字
【发布时间】:2017-03-13 21:44:27
【问题描述】:

我查看了这里的各种示例,但我无法弄清楚发生了什么。任何帮助表示赞赏。

我有一个文本文件,我想通过字典将其中的数字翻译成单词。

由于文本文件太长,我只提供一个简短的示例。 文本文件:

Movie: 12 15 11 13  
Director: 1 9 2 3  

我有一个由制表符分隔的文件,我认为我已将其制成字典。 字典文件:

1 Adam  
2 Lee  
3 Tom  
9 Jones  
11 Hostel  
12 WoW  
13 Home  
15 Surf

到目前为止,我的代码将运行在文本文件中,并只翻译它到达的第一个数字。

所以对于数字 11,它不会用 Hostel 替换它,而是用 AdamAdam 替换它。如果我将单词边界 \b 添加到数字中,则不会被替换。

代码:

f = [i.strip().split('\t') for i in open('dict')]  


with open('new.txt', 'w') as outfile, open('printnumbers') as infile:  
        for line in infile:  
            for oldword, newword in f:  
                line = line.replace(oldword, newword)  
    outfile.write(line)  

最终我希望能够用一个字典替换一行,用另一个替换下一行。我会尝试做更多的研究。

再次感谢。

【问题讨论】:

  • 字典是无序的,所以1 出现在11 之前的可能性当然很大。 调用你的变量一个“词”不会自动使它如此。
  • 嗯。我绝对明白你在说什么,我试图通过设置单词边界来让它搜索整个单词,但它只是没有替换任何东西。是因为文件根本错误吗?还是我错过了什么。

标签: python string list dictionary replace


【解决方案1】:

首先我们将从 dictfile 构建一个字典,然后我们将该字典应用到 txtfile

with open('dict.txt') as f:
    d = {a: b for line in f for a,b in line.split()}

with open('outfile.txt') as out, open('infile.txt') as infile:
    for line in infile:
        line = line.split()
        line = [d[word] if word in d else word for word in line]
        out.write(' '.join(line))

您的大问题是没有正确使用split。我还没有测试过这段代码,所以它可能需要根据文件的确切格式进行一些调整。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-06
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 2014-04-01
    • 2020-03-27
    • 1970-01-01
    相关资源
    最近更新 更多