gpt4 book ai didi

python - 搜索并用 python 替换

转载 作者:行者123 更新时间:2023-12-01 05:32:47 24 4
gpt4 key购买 nike

我正在尝试使用 python 进行搜索和替换

我要搜索和替换的文件是一个 3 列制表符分隔的文件,其中包含以下示例输入:

dog walk    1
cat walk 2
pigeon bark 3

我一直在使用的代码如下:

####open_file
import codecs
input_file=codecs.open("corpus3_tst","r",encoding="utf-8")
lines=input_file.readlines()
for word in lines:
words=word.rstrip()

# define method
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text

# text for replacement
my_text = words
print my_text

# dictionary with key:values.
# replace values
reps = {'dog':'ANIMAL', 'cat':'ANIMAL', 'pigeon':'ANIMAL'}

# bind the returned text of the method
# to a variable and print it
txt = replace_all(my_text, reps)
print txt

我的问题是它只用 ANIMAL 替换最后一个单词,并且它再次重复该行而不替换它。

输出:

pigeon  bark    3
ANIMAL bark 3

有人知道我的脚本哪里出了问题吗?我查看了 python Replace() 的文档,以及 stackoverflow 上的类似查询,似乎我正在遵循文档,所以我不知道我哪里出错了。

最佳答案

在下面的内容中,words 在每次迭代中都会被覆盖。循环后,words 仅包含最后一行。

for word in lines:
words=word.rstrip()
<小时/>

替换以下行:

lines=input_file.readlines()
for word in lines:
words=word.rstrip()

与:

words = input_file.read().rstrip()
<小时/>

使用正则表达式,可以简化程序。

import codecs
import re

with codecs.open("corpus3_tst","r",encoding="utf-8") as f:
words = f.read().rstrip()
pattern = r'dog|cat|pigeon'
#pattern = '|'.join(map(re.escape, ['dog', 'cat', 'pigeon']))
print re.sub(pattern, 'ANIMAL', words)

关于python - 搜索并用 python 替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19830388/

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