Как найти, если список элементов находится в другом списке элементов? - PullRequest
0 голосов
/ 26 марта 2020

Я загрузил текстовый файл как file_contents. цель этого - вычислить слова, появившиеся в моем текстовом файле после удаления знаков препинания и некоторых «неинтересных слов». Ниже мой код:

def calculate_frequencies(file_contents):
# Here is a list of punctuations and uninteresting words you can use to process your text
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", \
"we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", \
"their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", \
"have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", \
"all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"]
# LEARNER CODE START HERE

file_list = file_contents.split() #split words into individual string

for word in file_list:
    word= word.lower()#small letter

    if word in uninteresting_words:
        word = word.replace(word,"")
        return word
    if word in punctuations:
        word = word.replace(word,"")
        return word
print (word)

#create a dictionary
#add those words if they are not in dictionary , and count+1 for value
dict={}
n=0
for x in word:
    if x not in dict:
        n=1
        dict[x]=n
    else:
        n+=1
        dict[x]=n
    return dict
print(dict)

Calculate_frequencies (file_contents)

результат показывает ''. могу я узнать, что не так с моим кодом

1 Ответ

0 голосов
/ 26 марта 2020

Вы можете упростить ваш скрипт следующим образом:

from collections import Counter
from string import punctuation

# Remove punctuation from file_content
file_content = file_content.translate(str.maketrans("", "", punctuation))
# Get words
words = file_content.split()
# Keep only some words
words = [word for word in words if word not in uninteresting_words]
# Create the dictionary
d = Counter(words)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...