我是 python 新手。我想删除重复的单词
除了英文单词,我想删除所有其他单词和空行。
只有我想提取的纯英文单词。
我有一些文本文件,其中包含如下
aaa
bbb
aaa223
aaa
ccc
ddd
kei60:
sj@6999
jack02
jparkj
所以在处理重复之后我想得到以下结果
aaa
bbb
ccc
ddd
jparkj
以下是我尝试过的脚本源。
如果有人帮助我,非常感谢!谢谢!
# read a text file, replace multiple words specified in a dictionary
# write the modified text back to a file
import re
def replace_words(text, word_dic):
"""
take a text and replace words that match a key in a dictionary with
the associated value, return the changed text
"""
rc = re.compile('|'.join(map(re.escape, word_dic)))
def translate(match):
return word_dic[match.group(0)]
return rc.sub(translate, text)
def main():
test_file = "prxtest.txt"
# read the file
fin = open(test_file, "r")
str2 = fin.read()
fin.close()
# the dictionary has target_word:replacement_word pairs
word_dic = {
'.': '\n',
'"': '\n',
'<': '\n',
'>': '\n',
'!': '\n',
"'": '\n',
'(': '\n',
')': '\n',
'[': '\n',
']': '\n',
'@': '\n',
'#': '\n',
'$': '\n',
'%': '\n',
'^': '\n',
"&": '\n',
'*': '\n',
'_': '\n',
'+': '\n',
'-': '\n',
'=': '\n',
'}': '\n',
'{': '\n',
'"': '\n',
";": '\n',
':': '\n',
'?': '\n',
',': '\n',
'`': '\n',
'~': '\n',
'1': '\n',
'2': '\n',
'3': '\n',
'4': '\n',
"5": '\n',
'6': '\n',
'7': '\n',
'8': '\n',
'9': '\n',
'0': '\n',
' ': '\n'}
# call the function and get the changed text
str3 = replace_words(str2, word_dic)
# write changed text back out
fout = open("clean.txt", "w")
fout.write(str3)
fout.close()
if __name__ == "__main__":
main()