2012-02-06 10 views
3

Python 2.7.4でうまく動作していたPython 3.1.4で次のエラーが発生しました。Python:TypeError: 'リスト'オブジェクトを暗黙的にstrに変換できません

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

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! 

アップデート1:

私は、ファイル内にあるキーワードからリストを作成しようとしています。各行には1つのキーワードがあります。ファイルを正しく読んでいますか?

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'は、あなたが期待するように、リストの代わりに、文字列のようです。それは私が言うことができないそれらのうち、あなたはより多くのコードを提供する必要があります。 –

+0

ここのリストは何ですか?ライン1? re.search()は、リストではなく、検索するパターンと文字列を取ります。 – Sid

+0

@ NiklasB。あなたは正しいです。 Wordはリストです。詳細については私の編集質問をご覧ください。リストを適切な形式でインポートするのに問題があります。 – Zenvega

答えて

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): 

ここで使用されているのはジェネレータ式です。あなたはそれらについてよく知っておくべきです、それはまた、mapfilterを置き換えるのによく使われるlist 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ありがとうございました。キーワードリストは期待どおりの形式ではありません。ジェネレータオブジェクトなので、見ることができません。キーワード= ['Keyword1'、 'Keyword2'、...、 'Keywordn'] – Zenvega

+0

はい、リストの理解度を代わりに使うことができます: 'keywords = [x.strip()。lower()for x in f0.readlines()] ' –

+0

' .readlines() 'を削除してください。ここに行のリストを作成する必要はありません。 – jfs

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は、それが何であるかを理解するために印刷する必要があります。正規表現でwordの代わりに"".join(word)を使用することは可能ですが、そうではない可能性があります。

関連する問題