读取和检查文件中的连续单词
我想要读取一个文件里的单词,比如说,检查一下某个单词是不是“1”。如果这个单词是“1”,我还需要检查下一个单词是不是“two”。之后我还要做其他的事情。你能帮我检查一下“1”和“two”是不是连续出现的吗?
我用过
filne = raw_input("name of existing file to be proceesed:")
f = open(filne, 'r+')
for word in f.read().split():
for i in xrange(len(word)):
print word[i]
print word[i+1]
但是它没有效果。
2 个回答
0
我觉得你想从文件中打印两个连续的单词。
在你的代码里,你是一个一个字符地遍历,而不是一个一个单词地遍历,如果你是想这样做的话。
你可以按照下面的方式来实现:
f = open('yourFileName')
str1 = f.read().split()
for i in xrange(len(str1)-1): # -1 otherwise it will be index out of range error
print str1[i]
print str1[i+1]
如果你想检查某个单词是否存在,并且想查看它后面的单词,可以使用:
if 'wordYouWantToCheck' in str1:
index=str1.index('wordYouWantToCheck')
现在你有了你要找的单词的索引,你可以用 str1[index+1]
来检查它后面的单词。
不过,'index' 函数只会返回这个单词第一次出现的位置。为了达到你的目的,你可以使用 'enumerate' 函数。
indices = [i for i,x in enumerate(str1) if x == "1"]
这样会返回一个包含所有该单词出现位置的列表。
4
处理连续的项目最简单的方法就是使用zip
这个函数:
with open(filename, 'r') as f: # better way to open file
for line in f: # for each line
words = line.strip().split() # all words on the line
for word1, word2 in zip(words, words[1:]): # iterate through pairs
if word1 == '1' and word2 == 'crore': # test the pair
现在,你的索引(i
和i+1
)是在每个单词内部(也就是字符之间),而不是在列表中的单词之间。