2016-04-17 8 views
0

私は自分のプログラムに開いて読んだ3つのテキストファイルを持っています。それぞれには、n個の単語を抽出するためのスピーチが含まれています。私はその単語を小文字に変換しました。私は、後の分析のためにスプレッドシートに優れた単語をエクスポートする前にリストを作成した汚い言葉を取り除こうとしています。ouputから汚れた単語のリストを削除する方法

私はいくつかのサイトから複数のオプションを試しましたが、私は立ち往生しています。ここで

私が持っているものである:テキストファイルや他のもののために他のすべての変数などが呼び出され

hitList = ["am", "as", "is", "of", "the", "it", "or", "and", "to", "I", "a", "have", "you", "we", "they", "It's", "don't", "our", "so", "for", "-", ".", "but", "out"] 

txt = file.read().lower() 
words = txt.split() 
x = {} 
sumChars = len(words) 
sumLines = txt.count("\n") 
# Iterate through the words and append the list with new words 
for i in words: 
    if i in x: 
     try: 
      if x not in hitList: 
       x[i] += 1 
     except: 
      print("Oops... A word could not be added to the list.") 
      break 
      killCall() 
    else: x[i] = 1 
lst = [(x[i], i) for i in x] 
lst.sort() 
lst.reverse() 
sumWords = sum(x[i] for i in x) 
strsumChars = str(sumChars) 
strsumLines = str(sumLines) 
strsumWords = str(sumWords) 
# Convert the final list 'x' into lowercase values to ensure proper sorting 
print(filename + " contains " + strsumChars + " characters.") 
print(filename + " contains " + strsumLines + " lines.") 
print(filename + " contains " + strsumWords + " words. \n\n") 
print("The 30 most frequent words in " + filename + " are: ") 
g = 1 
for count, word in lst[:50]: 
    op = print('%2s. %4s %s' % (g, count, word)) 
    g+=1 

if savesheet == "Cleveland_Aug62015": 
    workbook = xlwt.Workbook() 
    col2 = "Word Count" 
    col3 = "Words" 
    worksheet = workbook.add_sheet("Cleveland_Aug62015", cell_overwrite_ok = True) 
    worksheet.write(0,0, col2) 
    worksheet.write(0,1, col3) 
    try: 
     for h, l in enumerate(lst[:50], start = 1): 
      for j, col in enumerate(l): 
       worksheet.write(h, j, col) 
     print("\n" + savesheet + " exported to Excel...") 
    except: print("\n" + savesheet + " unable to be saved to Excel...") 
    workbook.save(xlsfile + "_" + savesheet + ".xls") 

、私はここでの問題領域を掲載。私はまだそれをマークアップしていますので、私は、すべてを、捕獲されたエラーしていないなど

私が午前主な問題はここにある:私は作成する前に、汚い言葉を削除しようとしています

# Iterate through the words and append the list with new words 
for i in words: 
    if i in x: 
     try: 
      if x not in hitList: 
       x[i] += 1 
     except: 
      print("Oops... A word could not be added to the list.") 
      break 
      killCall() 
    else: x[i] = 1 
lst = [(x[i], i) for i in x] 
lst.sort() 
lst.reverse() 

出力リストは、汚い言葉が表示され続けます。

大幅にあなたが提供切り取ら下のコードであなたのif-else文では

ブランドン

+1

単語の少なくとも最初のインスタンスを取得しているので、言葉がhitList' 'である場合、あなたのelse文をチェックしません追加されました。 – RobertR

+4

私は[Counter'](https://docs.python.org/3/library/collections.html#collections.Counter)を使い、そこから 'pop()'を使って単語を削除し、最も一般的なものを返します'most_common() 'を使用している単語 –

+1

' if i in x'テストは、その単語が最初に処理されるときに常に失敗するため、すべての単語が 'x'に追加されます。 – snakecharmerb

答えて

0

を高く評価され、問題になっている単語がhitListであるかどうかをテストしているすべてのヘルプifではなく、elseには含まれていません。したがって、追加したくない単語は、少なくとも1回追加されています。

ifで行うのと同じ種類の保護をelseに提供すると役立ちます。または、より良いことに、if x not in hitList:にif-else全体をラップするだけです。

また、Andrea Corbellini氏によれば、Counterを使用すると、コードが大幅に簡略化されます。

+0

ヒットリストのif..else全体をラップしようとしましたが、それは実行されましたが、値を出力せず、ワードカウント出力に0ワードを示しました。 – BTBean

0

あなたのプログラムにはいくつかのエラーや非効率性があり、いくつかのPythonの慣用句には欠けています。ここ(のpython3のprint文を想定して)あなたのプログラムの最初の部分の手直しです:

from collections import Counter 
from operator import itemgetter 

# ... 

MOST_FREQUENT = 30 

hitList = {"am", "as", "is", "of", "the", "it", "or", "and", "to", "i", "a", "have", "you", "we", "they", "it's", "don't", "our", "so", "for", "-", ".", "but", "out"} 

rawText = file.read().lower() 

sumLines = rawText.count("\n") 

words = rawText.split() 

sumChars = sum(len(word) for word in words) # includes hitList 
# sumChars = sum(len(word) for word in words if word not in hitList) # excludes hitList 

wordCounts = Counter([word for word in words if word not in hitList]) 

sumWords = sum(wordCounts.values()) 

print(filename, "contains", sumChars, "characters.") 
print(filename, "contains", sumLines, "lines.") 
print(filename, "contains", sumWords, "words.", end="\n\n\n") 

wordHistogram = wordCounts.most_common(MOST_FREQUENT) 

print("The", MOST_FREQUENT, "most frequent words in", filename, "are:") 

for g, (word, count) in enumerate(wordHistogram[:MOST_FREQUENT]): 
    print('%2s. %4s %s' % (g + 1, count, word)) 

# ... 
+0

私はあなたの推薦を実装し、そのコードは機能しました。しかし、汚れた言葉は依然として出力に現れています。助言がありますか? – BTBean

+0

@BTBeanを実行したときにヒットリストの単語が表示されないので、私が含まれている変更されたコードを確認することをお勧めします。あなたは何かを見逃しているに違いない。 'Counter()'への引数であるリストの理解はヒットリストの単語を削除します。私の 'hitList'はリストではなく、セットであることに注意してください。それはあなたと私のコードが期待するものなので、要素を小文字にしました。 – cdlane

関連する問題