gpt4 book ai didi

python - 从 txt 文件中删除一些词替换一些其他词

转载 作者:行者123 更新时间:2023-11-28 20:47:41 24 4
gpt4 key购买 nike

我有一个包含多行文本的 txt 文件 (myText.txt)。

我想知道:

  • 如何创建需要删除的单词列表(我想自己设置单词)
  • 如何创建需要替换的单词列表

例如,如果 myText.txt 是:

    The ancient Romans influenced countries and civilizations in the following centuries.  
Their language, Latin, became the basis for many other European languages. They stayed in Roma for 3 month.
  • 我想删除“the”“和”“in”我想替换“古老”的“古老”
  • 我想替换“month”和“centuries”按“年”

最佳答案

你总是可以使用正则表达式:

import re

st='''\
The ancient Romans influenced countries and civilizations in the following centuries.
Their language, Latin, became the basis for many other European languages. They stayed in Roma for 3 month.'''

deletions=('and','in','the')
repl={"ancient": "old", "month":"years", "centuries":"years"}

tgt='|'.join(r'\b{}\b'.format(e) for e in deletions)
st=re.sub(tgt,'',st)
for word in repl:
tgt=r'\b{}\b'.format(word)
st=re.sub(tgt,repl[word],st)


print st

关于python - 从 txt 文件中删除一些词替换一些其他词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18326283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com