python - 搜索并用 python 替换

标签 python search replace

我正在尝试使用 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/

相关文章:

php - 跨 3 个数据库表的产品搜索

php - 将段落标签中的第一个字母包裹在跨度标签中

mysql - 是否可以只更改 mysql 中的小数部分?

python - PL/Python错误 "could not convert SPI error to Python exception"

python - 使用 Python 打印 PDF 文件

python - CQLSH复制错误类型错误: 'int' object is not iterable

使用meteor-easy-search按多个字段进行搜索

python - 如何使用 Python 获取 MongoDB 中特定键的值

elasticsearch - 如果是多重排序,Elastic Search的响应速度会变慢吗?[不是脚本排序]