私は自分のプログラムに開いて読んだ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文では
ブランドン
単語の少なくとも最初のインスタンスを取得しているので、言葉がhitList' 'である場合、あなたのelse文をチェックしません追加されました。 – RobertR
私は[Counter'](https://docs.python.org/3/library/collections.html#collections.Counter)を使い、そこから 'pop()'を使って単語を削除し、最も一般的なものを返します'most_common() 'を使用している単語 –
' if i in x'テストは、その単語が最初に処理されるときに常に失敗するため、すべての単語が 'x'に追加されます。 – snakecharmerb