我检查文件中某个单词的简单脚本似乎失败了,我似乎无法通过文档或搜索来解释它.代码如下.我相信我已经将它缩小到'in'运算符,因为打印代码本身并找到我正在寻找的单词而失败.如果好奇,这个脚本是在Quake源代码中找到某些关键字,因为我宁愿不查看30多个完整的源文件.任何帮助将不胜感激,谢谢!
import os
def searchFile(fileName, word):
file = open(os.getcwd() + "\\" + fileName,'r')
text = file.readlines()
#Debug Code
print text
if(word in text):
print 'Yep!'
else:
print 'Nope!'
Run Code Online (Sandbox Code Playgroud)
失败的原因是因为您正在检查单词是否在文本行内.只需使用read()方法并在那里签入或遍历所有行,每个行分别进行迭代.
# first method
text = file.read()
if word in text:
print "Yep!"
# second method
# goes through each line of the text checking
# more useful if you want to know where the line is
for i, line in enumerate(file):
if word in line:
print "Yep! Found %s on line: %s"%(word, i+1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1049 次 |
| 最近记录: |