Skip to main content
 首页 » 编程设计

python之用 DICT python 中的单词替换确切的数字

2024年10月17日7sky-heaven

我查看了此处的各种示例,但无法弄清楚发生了什么。感谢您的帮助。

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

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

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)   

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

再次感谢。

请您参考如下方法:

首先我们将从 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。我尚未测试此代码,因此可能需要根据文件的格式进行一些调整。