2017-05-21 6 views
1

こんにちは私は最初のテキストファイルを読み、各単語の頻度を数え、重複を取り除き、単語とその数がファイル内にあるリストのリストを作成する必要があります。リスト内のキーワードの頻度

私の2番目のテキストファイルにはキーワードが含まれています。最初のテキストファイルでこれらのキーワードの頻度を数え、インポート、dict、またはzipを使用せずに結果を返す必要があります。

私はファイルを開いて句読点などを削除したが、周波数を見つける手がかりはない。 私は.find()のアイデアで遊んだが、まだ運がない。

任意の提案は、これは現時点では私のコードでいただければ幸いです

def calculateFrequenciesTest(aString): 

    listKeywords= aString 
    listSize = len(listKeywords) 
    keywordCountList = [] 

    while listSize > 0: 
     targetWord = listKeywords [0] 
     count =0 
     for i in range(0,listSize): 
     if targetWord == listKeywords [i]: 
      count = count +1 

     wordAndCount = [] 
     wordAndCount.append(targetWord) 
     wordAndCount.append(count) 

     keywordCountList.append(wordAndCount) 

     for i in range (0,count): 
     listKeywords.remove(targetWord) 
     listSize = len(listKeywords) 

    sortedFrequencyList = readKeywords(keywordCountList) 

    return keywordCountList; 

編集 - 現在のアイデアの周りいじるキーワードファイル内のキーワードの頻度を見つけるように見えるではなく、最初のテキストファイルに私の最初のファイルをもう一度開くのですが、今回はそれをリストに入れません。私のエラーは何とか私のリストのリストの頻度を数えることから来ていると思う。

私は例として、単語のリストを取っています:これらはあなたが好きな何かを試すことができ、私は

[[['the', 66], 1], [['of', 32], 1], [['and', 27], 1], [['a', 23], 1], [['i', 23], 1]] 
+0

あなたができることは、それぞれのキーワードを調べ、そのキーワードがあなたの「頻度リスト」にある場合は、そのインデックスでそれを増やすだけです。 –

+0

これは基本的にはやりたいことですが、いくつかの方法で試してみましたが、うまくいきませんでした: –

答えて

1

を取得していた結果のタイプです。

word_list = ['hello', 'world', 'test', 'hello'] 
frequency_list = {} 
for word in word_list: 
    if word not in frequency_list: 
     frequency_list[word] = 1 
    else: 
     frequency_list[word] += 1 
print(frequency_list) 

RESULT: {'test': 1, 'world': 1, 'hello': 2} 

dictsに制約を入れているので、同じタスクを実行するために2つのリストを使用しました。私はそれがどれほど効率的であるかはわかりませんが、その目的に役立ちます。

word_list = ['hello', 'world', 'test', 'hello'] 
frequency_list = [] 
frequency_word = [] 
for word in word_list: 
    if word not in frequency_word: 
     frequency_word.append(word) 
     frequency_list.append(1) 
    else: 
     ind = frequency_word.index(word) 
     frequency_list[ind] += 1 

print(frequency_word) 
print(frequency_list) 

RESULT : ['hello', 'world', 'test'] 
     [2, 1, 1] 

あなたは私はあなたがこのためにCounterを使用する必要があります@berealに同意

+1

これは['collections.Counter'](https://docs.python.org/3.6/)ライブラリ/ collections.html#collections.Counter) – bereal

+0

@PaulRooney 'frequency_list'はdictですが、 – bereal

0

を望むようにあなたが再要因それを好むか、どのようにそれを変更することができます。私は、あなたが「輸入、口述、またはジップ」を望まないと言ったことを知っているので、この答えを無視して自由に感じてください。しかし、Pythonの主な利点の1つは、偉大な標準ライブラリであり、listが利用可能になるたびに、dict,collections.Counterreとなります。

あなたのコードから、CやJavaで使用したのと同じスタイルを使用したいという印象を得ています。私はもう少しでしようとお勧めしますpythonic。このように書かれたコードは、馴染みのないように見えるかもしれません。、そして慣れるまでに時間がかかります。しかし、もっと学びます。

Claryfying 達成しようとしているものが役に立ちます。あなたはPythonを学んでいますか?あなたはこの特定の問題を解決していますか?なぜあなたは輸入品、辞書、またはジップを使用できませんか?だからここ

は、それが(Pythonの2を使用してテスト)の価値がある何のための機能に組み込まれて利用提案(なしサードパーティ)です。ここで

#!/usr/bin/python 

import re   # String matching 
import collections # collections.Counter basically solves your problem 


def loadwords(s): 
    """Find the words in a long string. 

    Words are separated by whitespace. Typical signs are ignored. 

    """ 
    return (s 
      .replace(".", " ") 
      .replace(",", " ") 
      .replace("!", " ") 
      .replace("?", " ") 
      .lower()).split() 


def loadwords_re(s): 
    """Find the words in a long string. 

    Words are separated by whitespace. Only characters and ' are allowed in strings. 

    """ 
    return (re.sub(r"[^a-z']", " ", s.lower()) 
      .split()) 


# You may want to read this from a file instead 
sourcefile_words = loadwords_re("""this is a sentence. This is another sentence. 
Let's write many sentences here. 
Here comes another sentence. 
And another one. 
In English, we use plenty of "a" and "the". A whole lot, actually. 
""") 

# Sets are really fast for answering the question: "is this element in the set?" 
# You may want to read this from a file instead 
keywords = set(loadwords_re(""" 
of and a i the 
""")) 

# Count for every word in sourcefile_words, ignoring your keywords 
wordcount_all = collections.Counter(sourcefile_words) 

# Lookup word counts like this (Counter is a dictionary) 
count_this = wordcount_all["this"] # returns 2 
count_a = wordcount_all["a"] # returns 1 

# Only look for words in the keywords-set 
wordcount_keywords = collections.Counter(word 
             for word in sourcefile_words 
             if word in keywords) 

count_and = wordcount_keywords["and"] # Returns 2 
all_counted_keywords = wordcount_keywords.keys() # Returns ['a', 'and', 'the', 'of'] 
0

は無い輸入品とのソリューションです。小さな入力配列では少数の検索でも許容されるネストされた線形検索が使用されますが、入力が大きくなると扱いにくく遅くなります。

ここでも入力はかなり大きいですが、妥当な時間に処理します。あなたのキーワードファイルがもっと大きかった(私の言葉は3語しかない)と思っています。

ここで入力ファイルを取り、行を繰り返して句読点を削除し、スペースで区切り、すべての単語を単一のリストにまとめます。リストには二重引用符が含まれているので、それらを削除するために、二重引用符が一緒になるようにリストをソートし、それを反復して文字列とカウントを含む新しいリストを作成します。これは、同じ単語がリストに表示されている間はカウントをインクリメントし、新しい単語が表示されたら新しいエントリに移動することで実行できます。

これで単語の頻度リストが表示され、必要なキーワードを検索してカウントを取得できます。

入力テキストファイルはhereであり、キーワードファイルは1行に1つずつ、ファイル内のわずかな単語で一緒に綴じることができます。

のpython 3のコードは、それはあなたがバイナリ検索を使用するようにfindwordを変更することができるように傾斜した場合に該当する場合には、どのようにPythonの2

# use string.punctuation if you are somehow allowed 
# to import the string module. 
translator = str.maketrans('', '', '!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~') 

words = [] 
with open('hamlet.txt') as f: 
    for line in f: 
     if line: 
      line = line.translate(translator) 
      # py 2 alternative 
      #line = line.translate(None, string.punctuation) 
      words.extend(line.strip().split()) 

# sort the word list, so instances of the same word are 
# contiguous in the list and can be counted together 
words.sort() 

thisword = '' 
counts = [] 

# for each word in the list add to the count as long as the 
# word does not change 
for w in words: 
    if w != thisword: 
     counts.append([w, 1]) 
     thisword = w 
    else: 
     counts[-1][1] += 1 

for c in counts: 
    print('%s (%d)' % (c[0], c[1])) 

# function to prevent need to break out of nested loop 
def findword(clist, word): 
    for c in clist: 
     if c[0] == word: 
      return c[1] 
    return 0 

# open keywords file and search for each word in the 
# frequency list. 
with open('keywords.txt') as f2: 
    for line in f2: 
     if line: 
      word = line.strip() 
      thiscount = findword(counts, word) 
      print('keyword %s appear %d times in source' % (word, thiscount)) 

のために変更することを示しているが、そのはまだどこか近くであることを行っていませんa dict。制限がない場合はcollections.Counterが適切な解決策です。その迅速かつ少ないコード。