我想从给定文本文件中读取每个单词,然后想将这些单词与现有的英语字典进行比较,该单词可能是系统字典或任何其他方式。这是我尝试过的代码,但是在以下代码中,存在问题。以下代码读取括号或任何其他不必要的字符。
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)