我在python中查找文件中的一些单词。找到每个单词后,我需要从文件中读取下两个单词。我找了一些解决方案,但我找不到只读下一个字。
# offsetFile - file pointer
# searchTerms - list of words
for line in offsetFile:
for word in searchTerms:
if word in line:
# here get the next two terms after the word
感谢您的时间。
更新:只需要第一次出现。实际上,在这种情况下,只有一个字出现。
文件:
accept 42 2820 access 183 3145 accid 1 4589 algebra 153 16272 algem 4 17439 algol 202 6530
字:['access','algebra']
当我遇到'access'和'algebra'时搜索文件,我需要分别为183 3145和153 16272的值。
答案 0 :(得分:16)
处理此问题的一种简单方法是使用生成器从文件中一次生成一个单词来读取文件。
def words(fileobj):
for line in fileobj:
for word in line.split():
yield word
然后找到您感兴趣的单词并阅读接下来的两个单词:
with open("offsetfile.txt") as wordfile:
wordgen = words(wordfile)
for word in wordgen:
if word in searchterms: # searchterms should be a set() to make this fast
break
else:
word = None # makes sure word is None if the word wasn't found
foundwords = [word, next(wordgen, None), next(wordgen, None)]
现在foundwords[0]
是您找到的单词,foundwords[1]
是之后的单词,foundwords[2]
是其后的第二个单词。如果没有足够的单词,则列表中的一个或多个元素将为None
。
如果你想强制只能在一行内匹配,那就有点复杂了,但通常你可以把文件视为一个单词序列。
答案 1 :(得分:2)
如果您只需要检索两个第一个单词,请执行以下操作:
offsetFile.readline().split()[:2]
答案 2 :(得分:1)
word = '3' #Your word
delim = ',' #Your delim
with open('test_file.txt') as f:
for line in f:
if word in line:
s_line = line.strip().split(delim)
two_words = (s_line[s_line.index(word) + 1],\
s_line[s_line.index(word) + 2])
break
答案 3 :(得分:1)
def searchTerm(offsetFile, searchTerms):
# remove any found words from this list; if empty we can exit
searchThese = searchTerms[:]
for line in offsetFile:
words_in_line = line.split()
# Use this list comprehension if always two numbers continue a word.
# Else use words_in_line.
for word in [w for i, w in enumerate(words_in_line) if i % 3 == 0]:
# No more words to search.
if not searchThese:
return
# Search remaining words.
if word in searchThese:
searchThese.remove(word)
i = words_in_line.index(word)
print words_in_line[i:i+3]
对于'access','algebra',我得到了这个结果:
['access','183','3145'] ['代数','153','16272']