我在txt文件中有一个单词列表,每个单词都排在一行,旁边是其定义。但是,定义有时会使用该单词给出一个句子。我想将示例中重复的单词替换为符号〜。我该如何使用Python?
答案 0 :(得分:0)
假设单词和定义用#分隔:
with open('file.txt','r') as f:
for line in f:
myword,mydefinition=line.split("#")
if myword in mydefinition
mydefinition.replace(myword, "~")
答案 1 :(得分:0)
好的,这是我的示例,该示例将句子中每个单词的实例替换为另一个字符...
>>> my_string = "the quick brown fox jumped over the lazy dog"
>>> search_word = "the"
>>> replacement_symbol = "~"
>>> my_string.replace(search_word, replacement_symbol)
'~ quick brown fox jumped over ~ lazy dog'
很显然,这并不涉及文件的加载,而是逐行读取并省略单词的第一个实例...让我们稍微扩展一下。
words.txt
fox the quick brown fox jumped over the lazy dog
the the quick brown fox jumped over the lazy dog
jumped the quick brown fox jumped over the lazy dog
要阅读此内容,请剥离第一个单词,然后在其余行中替换该单词...
with open('words.txt') as f:
for line in f.readlines():
line = line.strip()
search_term = line.split(' ')[0]
sentence = ' '.join(line.split(' ')[1:])
sentence = sentence.replace(search_term, '~')
line = '%s %s' % (search_term, sentence)
print(line)
和输出...
fox the quick brown ~ jumped over the lazy dog
the ~ quick brown fox jumped over ~ lazy dog
jumped the quick brown fox ~ over the lazy dog