我想从给定的文本文件中读取每个单词,然后想要将这些单词与现有的英语词典进行比较,该词典可能是系统词典或任何其他方式。这是我尝试过的代码,但在下面的代码中,存在一个问题。以下代码读取括号或任何其他不必要的字符。
f=open('words.txt')
M=[word for line in f for word in line.split()]
S=list(set(M))
for i in S:
print i
我该怎么做?
您可以使用regex
过滤非字母:
import re
M = []
with open('words.txt') as f:
for line in f.readlines():
for word in line.split():
word = re.findall('[A-Za-z]+', word)
if word:
M.append(word[0])
S = list(set(M))
for i in S:
print(i)
输出:
computer
respect
incautiously
softened
satisfied
child
ideas
devoting
overtaken
等等
str.strip()
函数对您有用。以下代码删除所有圆括号:
f=["sagd sajdvsja jsdagjh () shdjkahk sajhdhk (ghj jskldjla) ...."]
M=[word.strip("()") for line in f for word in line.split()]
S=list(set(M))
for i in S:
print (i)