2014-01-05 19 views
1

我正在讀取每行上具有不同字符串的文件。我希望能夠在輸入字符串中搜索與文件中整行匹配的子字符串,然後保存該子字符串以便打印。這是我現在所擁有的:從python中的文件搜索字符串

wordsDoc = open('Database.doc', 'r', encoding='latin-1') 
words = wordsDoc.read().lower() 
matching = [string for string in words if string in op_text] 

但是這匹配每個字符。我將如何正確地做到這一點?

+0

'cardsDoc = wordsDoc'? – kojiro

+0

你想要輸入的字符串匹配整個行還是隻是其中的一部分? – kojiro

+0

對不起,cardsDoc = wordsDoc是的。我修正了這一點。 op_text是我需要搜索的輸入字符串。我想查看op_text中是否有與該文件中的整行匹配的子字符串,然後保存該子字符串。 – CrazyBurrito

回答

1

夫婦的評論:

首先,用with打開一個文件通常是更好:

with open('Database.doc', 'r', encoding='latin-1') as f: 
    # closes the file automagically at the end of this block... 

其次,沒有必要在整個文件中讀取,除非你正在做的事情與文件作爲一個整體。既然你正在尋找線,處理線逐一:

matches=[] 
with open('Database.doc', 'r', encoding='latin-1') as f: 
    for line in f: 
     if string in line.lower(): 
      matches.append(line) 

如果你想匹配整個行:

matches=[] 
with open('Database.doc', 'r', encoding='latin-1') as f: 
    for line in f: 
     if string == line.lower(): 
      matches.append(line) 

或者,更Pythonically,與列表理解:

with open('Database.doc', 'r', encoding='latin-1') as f: 
    matches=[line for line in f if line.lower()==string] 

等等

+0

它看起來像是在整個輸入字符串中匹配整行。我需要做的是將輸入文本的子字符串與文件中的整行進行匹配。所以如果輸入的文本中有任何提到的文件中的一行,它會保存該行 – CrazyBurrito

+0

我告訴你如何做到這一點。對於完全匹配,使用'if string == line.lower()'來測試這行是否包含匹配字符串,使用'if line.lower()'中的字符串'您聲明'我想要能夠搜索輸入字符串的子字符串**匹配整個行**在文件' – dawg

+0

我相信你的意思'如果line.lower()在字符串'因爲我想輸入中的子字符串匹配一條線,但是當我做它甚至從來沒有進入for循環 – CrazyBurrito

1

這將創建一個列表命名爲「匹配」,包含文件中所有與op_text中的字符串完全匹配的行,一次小寫。

with open('Database.doc', 'r', encoding='latin-1') as wordsDoc: 
    matching = [line for line in wordsDoc if op_text == line.lower()] 
+0

我認爲OP正試圖找出該鍵是否在該行的子字符串中,而不是如果它匹配整行。 –

+0

我認爲是相反的。 OP表示*匹配整行*的子字符串。這完全不清楚,我們應該要求OP澄清。 – kojiro

+0

我需要在op_text中找到與FILE中整行匹配的子字符串 – CrazyBurrito

1

我認爲這個想法是有一些搜索短語,如果它包含在文件的任何一行中,您想過濾掉這些行。

試試這個,它會比較行的下面的下裝版本,但是如果它包含search_key,它會從文件中返回原始的行。

with open('somefile.doc') as f: 
    matching = [line for line in f if search_key in line.lower()]