Python使用Regex替换单词列表

时间:2015-02-14 10:47:04

标签: python regex

我想使用RegEx模块替换单词列表,但即使经过多次尝试,我也失败了。

#full_list.txt
#Tab is the delimiter
#The left column is the list of words to be searched
#The right column is the list of words to be replaced

%!あ [×啞]    @#あ [啞]
%!あい きょう [\(愛嬌\)・\(愛▷敬\)]   @#あいきょう [愛嬌]
    .
    .
    .

我的代码如下:

import re

with open('full_list.txt', 'r', encoding='utf-8') as f:
    search_list = [line.strip().split('\t')[0] for line in f]

with open('full_list.txt', 'r', encoding='utf-8') as f:
    replace_list = [line.strip().split('\t')[1] for line in f]

with open('document.txt', 'r', encoding='utf-8') as f:
    content = f.read()

def replace_func(x, content):
    content = re.sub(search_list[x], replace_list[x], content)
    return content

x = 0
while x < 30:
    content = replace_func(x, content)
    x+=1

with open('new_document.txt', 'w', encoding='utf-8') as f:
    f.write(content)

运行代码后,有些单词可以替换,有些则无法替换。这些代码可能有什么问题?

1 个答案:

答案 0 :(得分:1)

如果您只想替换单词,请不要使用正则表达式,但替换字符串方法:

with open('full_list.txt', 'r', encoding='utf-8') as f:
    search_and_replace = [line.strip().split('\t') for line in f]

with open('document.txt', 'r', encoding='utf-8') as f:
    content = f.read()

for search, repl in search_and_replace:
    content = content.replace(search, repl)

with open('new_document.txt', 'w', encoding='utf-8') as f:
    f.write(content)