2012-02-06 40 views
3

我在Python 2.7.4中使用Python 3.1.4時遇到以下錯誤。python:TypeError:不能將'list'對象隱式轉換爲str

TypeError: Can't convert 'list' object to str implicitly. I get the error on the if statement. Please let me know how to fix this. Thanks! 

for word in keywords: # Iterate through keywords 
    if re.search(r"\b"+word+r"\b",line1):   #Search kewords in the input line 

UPDATE1:

我試圖創建關鍵字列表,這是在一個文件中。每行有一個關鍵字。我正確讀取文件嗎?

keyword_file=r"KEYWORDS.txt" 
f0=open(keyword_file,'r') 
keywords = map(lambda a: a.split('\n'),map(str.lower, f0.readlines())) 

關鍵字文件包含:

Keyword1 
Keyword2 
. 
. 
. 
Keywordn 

我想叫keywords = ['Keyword1','Keyword2',...,'Keywordn']

+2

是'word'或'line1'似乎是列表,而不是一串,像你期望的那樣。哪些是我不能告訴,你必須提供更多的代碼。 – 2012-02-06 18:48:25

+0

這是什麼清單?一號線? re.search()採用模式和字符串進行搜索,而不是列表。 – Sid 2012-02-06 18:49:04

+0

@NiklasB。你是對的。 Word是一個列表。請參閱我的編輯問題以獲取更多信息。我無法以正確的格式導入列表。 – Zenvega 2012-02-06 18:53:46

回答

3

您將行分割,但它們已被readlines()拆分。這應該工作:

# actually no need for readline() here, the file object can be 
# directly used to iterate over the lines 
keywords = (line.strip().lower() for line in f0) 
# ... 
for word in keywords: 
    if re.search(r"\b"+word+r"\b",line1): 

這裏使用的是一個生成器表達式。您應該瞭解這些內容,它們非常方便,以及通常可用於替換mapfilterlist comprehensions

注意,這可能是更高性能的循環之前創建的正則表達式,像這樣:

keywords = (line.strip() for line in f0) 
# use re.escape here in case the keyword contains a special regex character 
regex = r'\b({0})\b'.format('|'.join(map(re.escape, keywords))) 
# pre-compile the regex (build up the state machine) 
regex = re.compile(regex, re.IGNORECASE) 

# inside the loop over the lines 
if regex.search(line1) 
    print "ok" 
+0

謝謝Niklas。關鍵字列表不是期望的格式。我無法查看它,因爲它是一個生成器對象。它可以看起來像關鍵字= ['關鍵字1','關鍵字2',...,'Keywordn'] – Zenvega 2012-02-06 19:17:06

+0

是的,通過使用列表理解,而不是:關鍵字= [x.strip()。lower()for x in f0.readlines()]' – 2012-02-06 19:18:00

+0

drop'.readlines()'。這裏不需要創建行列表。 – jfs 2012-02-06 21:38:07

1

名單就意味着你的關鍵字對象包含列表。

# this is valid: 
import re 
keywords=["a","b","c"] 

for word in keywords: # Iterate through keywords 
    if re.search(r"\b"+word+r"\b",line1): 
     print "ok" 

# this is not valid. This is the kind of error you get:  
keywords=[["a","b"],"c"] 

for word in keywords: # Iterate through keywords 
    if re.search(r"\b"+word+r"\b",line1): 
     print "ok" 

您應該打印word以確保您瞭解它是什麼。在您的正則表達式中,您可能(但不太可能)使用"".join(word)而不是word

相關問題