2016-08-03 2 views
1

Я создаю список наиболее часто встречающихся слов в текстовом файле. Но я продолжаю получать слова и их притяжательные версии. Как iphone и iphone. Мне также нужно снять запятую после слов, таких как iphone и iphone, в моих результатах. Я хочу считать эти слова единым целым. Вот мой весь код.Удаление препинания из текстового файла, включая 's ​​и запятые

# Prompuser for text file to analyze 
filename = input("Enter a valid text file to analyze: ") 

# Open file and read it line by line 
s = open(filename, 'r').read().lower() 

# List of stop words that are not inportant to the meaning of the content 
# These words will not be counted in the number of characters, or words. 
stopwords = ['a', 'about', 'above', 'across', 'after', 'afterwards'] 
stopwords += ['again', 'against', 'all', 'almost', 'alone', 'along'] 
stopwords += ['already', 'also', 'although', 'always', 'am', 'among'] 
stopwords += ['amongst', 'amoungst', 'amount', 'an', 'and', 'another'] 
stopwords += ['any', 'anyhow', 'anyone', 'anything', 'anyway', 'anywhere'] 
stopwords += ['are', 'around', 'as', 'at', 'back', 'be', 'became'] 
stopwords += ['because', 'become', 'becomes', 'becoming', 'been'] 
stopwords += ['before', 'beforehand', 'behind', 'being', 'below'] 
stopwords += ['beside', 'besides', 'between', 'beyond', 'bill', 'both'] 
stopwords += ['bottom', 'but', 'by', 'call', 'can', 'cannot', 'cant'] 
stopwords += ['co', 'computer', 'con', 'could', 'couldnt', 'cry', 'de'] 
stopwords += ['describe', 'detail', 'did', 'do', 'done', 'down', 'due'] 
stopwords += ['during', 'each', 'eg', 'eight', 'either', 'eleven', 'else'] 
stopwords += ['elsewhere', 'empty', 'enough', 'etc', 'even', 'ever'] 
stopwords += ['every', 'everyone', 'everything', 'everywhere', 'except'] 
stopwords += ['few', 'fifteen', 'fifty', 'fill', 'find', 'fire'] 
stopwords += ['five', 'for', 'former', 'formerly', 'forty', 'found'] 
stopwords += ['four', 'from', 'front', 'full', 'further', 'get', 'give'] 
stopwords += ['go', 'had', 'has', 'hasnt', 'have', 'he', 'hence', 'her'] 
stopwords += ['here', 'hereafter', 'hereby', 'herein', 'hereupon', 'hers'] 
stopwords += ['herself', 'him', 'himself', 'his', 'how', 'however'] 
stopwords += ['hundred', 'i', 'ie', 'if', 'in', 'inc', 'indeed'] 
stopwords += ['interest', 'into', 'is', 'it', 'its', 'itself', 'keep'] 
stopwords += ['last', 'latter', 'latterly', 'least', 'less', 'ltd', 'made'] 
stopwords += ['many', 'may', 'me', 'meanwhile', 'might', 'mill', 'mine'] 
stopwords += ['more', 'moreover', 'most', 'mostly', 'move', 'much'] 
stopwords += ['must', 'my', 'myself', 'name', 'namely', 'neither', 'never'] 
stopwords += ['nevertheless', 'next', 'nine', 'no', 'nobody', 'none'] 
stopwords += ['noone', 'nor', 'not', 'nothing', 'now', 'nowhere', 'of'] 
stopwords += ['off', 'often', 'on','once', 'one', 'only', 'onto', 'or'] 
stopwords += ['other', 'others', 'otherwise', 'our', 'ours', 'ourselves'] 
stopwords += ['out', 'over', 'own', 'part', 'per', 'perhaps', 'please'] 
stopwords += ['put', 'rather', 're', 's', 'same', 'see', 'seem', 'seemed'] 
stopwords += ['seeming', 'seems', 'serious', 'several', 'she', 'should'] 
stopwords += ['show', 'side', 'since', 'sincere', 'six', 'sixty', 'so'] 
stopwords += ['some', 'somehow', 'someone', 'something', 'sometime'] 
stopwords += ['sometimes', 'somewhere', 'still', 'such', 'take'] 
stopwords += ['ten', 'than', 'that', 'the', 'their', 'them', 'themselves'] 
stopwords += ['then', 'thence', 'there', 'thereafter', 'thereby'] 
stopwords += ['therefore', 'therein', 'thereupon', 'these', 'they'] 
stopwords += ['thick', 'thin', 'third', 'this', 'those', 'though', 'three'] 
stopwords += ['three', 'through', 'throughout', 'thru', 'thus', 'to'] 
stopwords += ['together', 'too', 'top', 'toward', 'towards', 'twelve'] 
stopwords += ['twenty', 'two', 'un', 'under', 'until', 'up', 'upon'] 
stopwords += ['us', 'very', 'via', 'was', 'we', 'well', 'were', 'what'] 
stopwords += ['whatever', 'when', 'whence', 'whenever', 'where'] 
stopwords += ['whereafter', 'whereas', 'whereby', 'wherein', 'whereupon'] 
stopwords += ['wherever', 'whether', 'which', 'while', 'whither', 'who'] 
stopwords += ['whoever', 'whole', 'whom', 'whose', 'why', 'will', 'with'] 
stopwords += ['within', 'without', 'would', 'yet', 'you', 'your'] 
stopwords += ['yours', 'yourself', 'the', '—', 'The', '9', '5', 'just'] 
# count characters 
num_chars = len(s) 

# count lines 
num_lines = s.count('\n') 

# Split the words in the file 
words = s.split() 

# Create empty dictionary 
d = {} 

for i in d: 
    i = i.replace('.','') 
    i = i.replace(',','') 
    i = i.replace('\'','') 
    d.append(i.split()) 

# Add words to dictionary if they are not in it already. 

for w in words: 
    if w in d: 

#increase the count of each word added to the dictionary by 1 each time it appears 
     d[w] += 1 
    else: 
     d[w] = 1 

# Find the sum of each word's count in the dictionary. Drop the stopwords. 
num_words = sum(d[w] for w in d if w not in stopwords) 

# Create a list of words and their counts from file 
# in the form number of occurrence word count word 
lst = [(d[w], w) for w in d if w not in stopwords] 

# Sort the list of words by the count of the word 
lst.sort() 

# Sort the word list from greatest to least 
lst.reverse() 

# Print number of characters, number of lines rea, then number of words 
# that were counted minus the stop words. 
print('Your input file has characters = ' + str(num_chars)) 
print('Your input file has num_lines = ' + str(num_lines)) 
print('Your input file has num_words = ' + str(num_words)) 

# Print the top 30 most frequent words 
print('\n The 30 most frequent words are \n') 

# Start list at 1, the most most frequent word 
i = 1 

# Create list for the first 30 frequent words 
for count, word in lst[:30]: 

# Create list with the number of occurrence the word count then the word 
    print('%2s. %4s %s' % (i, count, word)) 
# Increase the list number by 1 after each entry 
    i += 1 

Некоторые из моих результатов.

1. 40 iphone 

2. 15 users 

3. 12 iphone’s 

4.  9 music 

5.  9 apple 

6.  8 web 

7.  7 new 

Любая помощь была бы принята с благодарностью. Thank you

+0

Только в стороне, списки могут охватывать несколько строк, поэтому '['a',' может заканчивать несколько строк позже '' just '] 'без всех' + = ' – beroe

ответ

0

Вы должны сказать for i in words: не for i in d: Вы повторяете пустой словарь во время шагов замены, поэтому ничего не меняется. Просто удалите этот цикл и переместите шаги замещения в начало цикла for w in words:, так что вам нужно сделать только один проход.

Я бы повторить, что целый раздел Thusly:

for w in words: 
    w = w.replace('.','').replace(',','').replace('\'','').replace("’","") 
    d[w] = d.get(w,0) + 1 

Как это сейчас, вы также пытаются разделить i перед добавлением в словарь. Он уже раскололся. Кроме того, вам нужен ключ: значение для словаря. Просто дайте ему значение нуля в этот момент ?, так что позже вы можете подсчитать случаи без тестирования?

Вместо тестирования if w in d: это будет сотни (даже тысячи раз быстрее), чтобы использовать .get() со значением по умолчанию, равным нулю (возвращается, если w не найден), как показано на рисунке выше.

+0

Спасибо за вашу помощь. @beroe, но у меня все еще есть проблема с iphone и iphone в моем списке. Я очистил свой код, как вы предлагали, и исправил некоторые слова. –

+0

Апостроф в вашем списке - это «кудрявая цитата». Вам также потребуется заменить это, что может потребовать строки Unicode. – beroe

+0

Я думаю, что я отредактировал свой ответ, чтобы заменить апостроф, но делать это на iPhone, поэтому не могу точно сказать. – beroe