2017-09-23 11 views
0

この関数を使用してサイトを検索し、特定の商品が興味があるかどうかを確認しています。まず、ページからhtmlを取得し、興味のある項目を検索します。アイテムが見つかると、変数 'endresult'に次の行(rangenumberで示される)を追加します。次に、endresultのキーワード( "sale")を検索します。その時点で、キーワードが存在するかどうか通知します。
endresultを出力すると出力にキーワードが含まれますが、関数の最後のif文はこれにもかかわらず常に "keyword is missing"を返すため、なぜうまくいかないのですか? 「=」の前にendresult += str(f.readline())予告「+」:文字列の検索でfalseが返されますが、出力に文字列が表示される

def bargainscraper(self, website, item, keyword,rangenum): 
    request = urllib.request.Request(website) 
    response = urllib.request.urlopen(request) 
    data = response.read() 
    html = str(data) 
    data1 = html2text.html2text(html) 
    fw = open('result1.txt', 'w') 
    fw.write(str(data1)) 
    fw.close() 
    with open('result1.txt', 'r') as f: 
     for line in f: 
      if item in line: 
       for x in range(rangenum): 
        endresult = str(f.readline()) 
        print (endresult) 
    if keyword in endresult: 
     print("keyword is present") 
    else: 
     print("keyword is missing") 
+2

あなたが 'に行を追加していません最終結果。読んだ行ごとに置き換えているので、最後の行だけが含まれます。最終的にその価値を印刷することは、これを明確にします。 – interjay

+0

HI interjay、どうすればendresultにすべての行が含まれていることを確認できますか? – nmh

+0

@nph 'list 'を使って' endresult'のすべての値を保持することができます。そして、後で、それぞれの 'endresult'を繰り返して' keyword 'と一致させることができます。 –

答えて

0

は、おそらくのようなもので、それを上書きするのではなくendresultを連結する必要があります。

+0

これは動作しません。 'UnboundLocalError:ローカル変数' endresult 'が割り当て前に参照されているというエラーが表示されます。 – nmh

+0

'$ endresult'が空であるかどうかを確認する' if'ステートメントを追加する必要があります'='使用しない場合は、 '+ =' ...を使用します。別の方法は、あらかじめ空として宣言することです。 –

0

私は、forループの外でキーワードについて、そのファイルを検索するforループ内のファイルへのendresultを書くことは私が探していた答えだったが見つかりました:

def bargainscraper(self, website, item, keyword,rangenum): 
       request = urllib.request.Request(website) 
       response = urllib.request.urlopen(request) 
       data = response.read() 
       html = str(data) 
       data1 = html2text.html2text(html) 
       fw = open('result1.txt', 'w') 
       fw.write(str(data1)) 
       fw.close() 
       with open('result1.txt', 'r') as f: 
         for line in f: 
           if item in line: 
             for x in range(rangenum): 
               endresult = str(f.readline()) 
               # the 'a' switch is used to append 
               with open('result2.txt', 'a') as n: 
                 n.write(endresult) 
       # This is outside of the for loop as otherwise it will iterate for each line of the rangenum 
       if keyword in open('result2.txt').read(): 
         print ("keyword is present") 
       else: 
         print ("keyword is missing") 
関連する問題