2013-04-09 41 views
1

我試圖在長度爲7個字母幷包含字母a,b,c,e和r的文本文件中查找單詞。到目前爲止,我有這個:在包含某些字符的文本文件中查找一個字,並且該字符的長度爲

import re 

file = open("dictionary.txt","r") 
text = file.readlines() 
file.close() 


keyword = re.compile(r'\w{7}') 

for line in text: 
    result = keyword.search (line) 
    if result: 
     print (result.group()) 

任何人都可以幫助我嗎?

+2

這個單詞是否只包含* a *,'b','c','e'和'r'字母或是否至少包含*這些字母? – 2013-04-09 19:45:58

+0

@ Becs1990您應該養成習慣,通過點擊表決底下的選中標記來標記解決問題的答案。 – FrankieTheKneeMan 2013-04-10 08:39:41

回答

2

你不僅需要匹配單詞字符,而且這個詞邊界

keyword = re.compile(r'\b\w{7}\b') 

\b停泊在單詞的開始或結束匹配,字限制準確 7字符。

它會更有效,如果你通過文件中的行由行是循環,而不是讀它全部入內存一氣呵成:

import re 

keyword = re.compile(r'\b\w{7}\b') 

with open("dictionary.txt","r") as dictionary:  
    for line in dictionary: 
     for result in keyword.findall(line): 
      print(result) 

使用keyword.findall()給我們的所有列表比賽就行了。

要檢查是否匹配有它需要的字符中的至少一個,我個人只使用了一組相交測試:

import re 

keyword = re.compile(r'\b\w{7}\b') 
required = set('abcer') 

with open("dictionary.txt","r") as dictionary:  
    for line in dictionary: 
     results = [required.intersection(word) for word in keyword.findall(line)] 
     for result in results 
      print(result) 
+0

這不會從文件中返回任何東西。返回的單詞可以包含任何或所有這些字母。我感到很困惑。 – Becs1990 2013-04-09 20:00:28

+0

@ Becs1990:請添加一些與您的問題相匹配的示例詞。 – 2013-04-09 20:03:53

+0

我的字典裏總共有24,000個單詞。但是,例如:鮑魚 放棄 abbrevi abdicat 腹部 abdomin 阿貝爾 阿伯爾森 Aberdee Abernat – Becs1990 2013-04-09 20:07:42

1
\b(?=\w{0,6}?[abcer])\w{7}\b 

這就是你想要的正則表達式。它的工作原理是使用基本形式的七個字母的單詞(\b\w{7}\b),並添加一個前瞻 - 一個零寬度的斷言,向前看,並試圖找到你需要的一個字母。細目:

\b   A word boundary 
(?=   Look ahead and find... 
    \w  A word character (A-Za-z0-9_) 
    {0,6}  Repeated 0 to 6 times 
    ?   Lazily (not necessary, but marginally more efficient). 
    [abcer] Followed by one of a, b, c, e, or r 
)    Go back to where we were before (just after the word boundary 
\w   And match a word character 
{7}   Exactly seven times. 
\b   Then one more word Boundary. 
+0

謝謝soooooo多!有用!最後!你是一個傳奇! – Becs1990 2013-04-09 20:53:48

相關問題