如何解决如何使用Python将文本文件中仅出现一次的单词替换为其他单词?
我无法替换在文本文件中只出现一次的单词。
假设我有一个文本文件,其中包含:
我有一支笔, 我有一个苹果, !!阿普尔彭 我有支笔, 我有菠萝 h!菠萝笔。
我期望得到的结果是
我有一支笔,我有一个苹果,呃! (唯一),我有一支笔,我有菠萝,嗯! (唯一)。
这是我在Python中的示例代码:
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 (unique),(unique)! (unique).'
您可以对整个文本文件或逐行应用相同的逻辑。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。