搜索用户输入的txt文件。

Python你好,这是我的第一次尝试,我想实现的是一个脚本,该脚本将要求用户输入,搜索一个txt文件并显示输出或给未找到信息。理想我想问用户一旦第一个输出为进一步实现用户输入如果需要,否则退出程序。然而,如果实现了第一个目标会很高兴。下面是我可以,问题是它是打破第一次发现后,下落我知道有额外的txt文件中的匹配。我想我可能需要更换,如果一段时间,让我尝试错误,我无法工作。

选择 | 换行 | 行号
  1. print"\nSEARCHING NUMBERS"  
  2.  
  3. print "\nPlease Enter the Number 1, 2, 3, 4 or 5."  
  4.  
  5. text_file = open("read_it.txt", "r")  
  6.  
  7. word = raw_input("Type the Number you want to check: ") word = word.upper()  
  8.  
  9. print "\nnumber." 
  10. for lines in text_file:  
  11.  
  12. # if the line does not contain the typed number 
  13. # then continue to the next line      
  14.  
  15. if ''.join(lines).find(word) == -1:continue         
  16. print lines 
  17.  
  18. break 
  19. else:        
  20.  
  21. print "Not found"     # Executed whenever break above is NOT executed 
  22. print  raw_input("\n\nPress the enter key to exit.")  
  23.  
  24. text_file.close()  

我只是一个初学者,所以将不胜感激任何帮助或建议谢谢。L:)

# 回答1

选择 | 换行 | 行号
  1. # if the line does not contain the typed number
  2. # then continue to the next line
  3. if ''.join(lines).find(word) == -1:continue
  4. print lines
  5. break
  6. else:
  7.     print "Not found"     # Executed whenever break above is NOT executed
  8.  

这段代码是困惑。我不知道哪些代码应该是if块。继续跳直接循环的顶部。没必要做任何违反或打印任何东西后继续使用。现在,你不需要继续使用或破坏;一个简单的if - else应该做它。

选择 | 换行 | 行号
  1. if the word is found:
  2.     print "Found"
  3. else:
  4.     print "Not found"
  5.  

至于检查如果发现这个词,不是nessecary发现功能。只是使用的运算符:

选择 | 换行 | 行号
  1. if word in lines:
  2.     print "Found"
  3.  

希望这个有帮助。

# 回答2

由于箱鲀,我不断地得到一个"无效语法"

选择 | 换行 | 行号
  1. if the 'word' is found:

.非常感谢你的反馈,可以看到一片混乱,(这是作者的真实写照)。L: (

# 回答3

对不起,这是伪代码。使用第二个代码使用的运营商找到这个词。计划越多,越少你会混淆。
# 回答4

谢谢你箱鲀。:)

标签: python

添加新评论