簡體   English   中英

如果字符串在文本文件中並打印行,如何檢查Python?

[英]How to check in Python if string is in a text file and print the line?

我想要做的是檢查是否在文本文件中找到此字符串。 如果是,我希望它打印出該行,否則打印出一條消息。

到目前為止,我已實現此代碼:

 def check_string(string):

     w = raw_input("Input the English word: ")
        if w in open('example.txt').read():
            for w.readlines():
                print line
        else:
            print('The translation cannot be found!')

我已經嘗試過實現,但是我遇到了語法錯誤。

它說:

該行的語法無效 - 對於w.readlines():

關於如何使用這行代碼的任何想法?

你應該嘗試這樣的事情:

import re
def check_string():
    #no need to pass arguments to function if you're not using them
    w = raw_input("Input the English word: ")

    #open the file using `with` context manager, it'll automatically close the file for you
    with open("example.txt") as f:
        found = False
        for line in f:  #iterate over the file one line at a time(memory efficient)
            if re.search("\b{0}\b".format(w),line):    #if string found is in current line then print it
                print line
                found = True
        if not found:
            print('The translation cannot be found!')

check_string() #now call the function

如果您正在搜索確切的單詞而不僅僅是子字符串,那么我建議在這里使用regex

例:

>>> import re
>>> strs = "foo bar spamm"
>>> "spam" in strs        
True
>>> bool(re.search("\b{0}\b".format("spam"),strs))
False

通過in運算符中使用in這是一個更簡單的示例:

w = raw_input("Input the English word: ") # For Python 3: use input() instead
with open('foo.txt') as f:
    found = False
    for line in f:
        if w in line: # Key line: check if `w` is in the line.
            print(line)
            found = True
    if not found:
        print('The translation cannot be found!')

如果您想知道字符串的位置,那么您可以使用find()而不是in運算符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM