我使用python打开文件以查找打开的文件中是否存在预定义的单词集。我将一组预定义的单词放在一个列表中,并打开了需要测试的文件。现在有什么方法可以用python而不是行来提取单词。这使我的工作变得更容易。从文件中提取单词
Q
从文件中提取单词
3
A
回答
7
import re
def get_words_from_string(s):
return set(re.findall(re.compile('\w+'), s.lower()))
def get_words_from_file(fname):
with open(fname, 'rb') as inf:
return get_words_from_string(inf.read())
def all_words(needle, haystack):
return set(needle).issubset(set(haystack))
def any_words(needle, haystack):
return set(needle).intersection(set(haystack))
search_words = get_words_from_string("This is my test")
find_in = get_words_from_string("If this were my test, I is passing")
print any_words(search_words, find_in)
print all_words(search_words, find_in)
回报
set(['this', 'test', 'is', 'my'])
True
1
你可以做几件事情
- 呼叫file.readlines()和分裂整个文本您想要的分隔符,如果你的文字并不大
- 调用read(),并做到这一点,在字节一时间
退房的pydocs文件 - http://docs.python.org/release/2.5.2/lib/bltin-file-objects.html
1
此代码将显示哪些话是存在于文件中,因为这个词精确匹配,和我不在标点符号或其他字符之前或之后,并且是相同的情况。通过一些小的调整,代码可以变得更宽容。
words = set(['hello', 'world', 'testing'])
f = open('testfile.txt', 'rb')
data = set(f.read().split())
print words.intersection(data)
一个完美的解决方案...如果该文件是太聪明large..any解决 – nikhil 2011-02-10 23:09:38