如何使用Python将只出现一次的单词替换为文本文件中的其他单词?
我在替换文本文件中只出现一次的单词时遇到问题 假设我有一个文本文件,其中包含: 我有一支钢笔, 我有一个苹果, 啊!!阿普尔彭, 我有一支钢笔, 我有菠萝, 啊!!菠萝粉 我期望得到的结果是 我有一支钢笔,我有一个苹果,嗯!(独一无二),我有一支钢笔,我有菠萝,嗯!(独一无二) 下面是我用Python编写的示例代码:如何使用Python将只出现一次的单词替换为文本文件中的其他单词?,python,text-files,Python,Text Files,我在替换文本文件中只出现一次的单词时遇到问题 假设我有一个文本文件,其中包含: 我有一支钢笔, 我有一个苹果, 啊!!阿普尔彭, 我有一支钢笔, 我有菠萝, 啊!!菠萝粉 我期望得到的结果是 我有一支钢笔,我有一个苹果,嗯!(独一无二),我有一支钢笔,我有菠萝,嗯!(独一无二) 下面是我用Python编写的示例代码: new_unique_word_file = open('new_unique_word.txt' , 'w' , encoding='utf-8') with open('new
new_unique_word_file = open('new_unique_word.txt' , 'w' , encoding='utf-8')
with open('new_train.txt', 'r', encoding='utf-8') as unique_word_file:
line = unique_word_file.readlines()
counts = dict()
for each_line in line:
each_line.split()
for word in each_line:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
for each_word in counts:
count_word = counts[each_word]
if count_word == 1:
modified_line = each_line.replace(each_word ,'(unique)')
new_unique_word_file.write(modified_line)
我得到的结果是非常奇怪的,我真的找不到一个合适的方法来做这件事。
谢谢你的帮助
更新,我刚刚发现我犯了一个错误。输出文件应该是
我有一支笔,我有(独一无二的)苹果,(独一无二的)(独一无二的),我有一支笔,我有菠萝,(独一无二的)(独一无二的)。你可以利用
regex
查找所有减去标点/空格的单词。然后只需使用string.count()
检查每个单词的出现次数
但是,您的示例与您的预期输出不匹配,因为有更多的独特单词,而不是您指定的
import re
string = "I have a pen, I have an apple, Uhhh! Applepen, I have a pen, I have pineapple, Uhh! Pineapplepen."
for word in re.findall('[a-zA-Z]\w*', string):
if string.count(word) == 1:
print(f"Unique word found: {word}")
string = string.replace(word, '(unique)')
输出:
Unique word found: an
Unique word found: Uhhh
Unique word found: Applepen
Unique word found: pineapple
Unique word found: Uhh
Unique word found: Pineapplepen
>>> string
'I have a pen, I have (unique) apple, (unique)! (unique), I have a pen, I have (unique), (unique)! (unique).'
您可以对整个文本文件应用相同的逻辑,也可以逐行应用相同的逻辑。为什么菠萝没有替换为(唯一)?“Uhhh!”“Uhh!”也是?不确切地知道预期结果是什么。从原始文本文件中,通过比较所有单词,菠萝蛋白酶和苹果蛋白酶应该与任何其他单词区别开来。因此,当查看整个文件时,我们可以看到这两个唯一的单词,然后我想用“(unique)”替换它们。我的错,我应该包括“啊!”嗯!,还有“安”。