简体   繁体   中英

Python: KeyError: 'it'

I am trying to do url text summarize using nltk in python3 but i am not sure why it's showing KeyError. Here is my code:

flasexam.py

import bs4 as bs
import urllib.request
import re
import heapq
import nltk

scraped_data = urllib.request.urlopen('https://en.wikipedia.org/wiki/Machine_learning')
article = scraped_data.read()

parsed_article = bs.BeautifulSoup(article,'lxml')

paragraphs = parsed_article.find_all('p')

article_text = ""

for p in paragraphs:
    article_text += p.text

article_text = re.sub(r'\[[0-9]*\]', ' ', article_text)
article_text = re.sub(r'\s+', ' ', article_text)

formatted_text = re.sub('[^a-zA-Z]', ' ', article_text)
formatted_text = re.sub(r'\s+', ' ', formatted_text)

sentence_list = nltk.sent_tokenize(article_text)

stopwords = nltk.corpus.stopwords.words('english')

word_freq = {}
for word in nltk.word_tokenize(formatted_text):
    if word not in stopwords:
        if word not in word_freq.keys():
            word_freq[word] = 1
        else:
            word_freq[word] += 1

max_freq = max(word_freq.values())
for word in word_freq.keys():
    word_freq[word] = (word_freq[word]/max_freq)

sentence_scores = {}
for sent in sentence_list:
    for word in nltk.word_tokenize(sent.lower()):
        if len(sent.split(' ')) < 30:
            if sent not in sentence_scores.keys():
                sentence_scores[sent] = word_freq[word]
            else:
                sentence_scores[sent] += word_freq[word]

summary_sentences = heapq.nlargest(7, sentence_scores, key=sentence_scores.get)

summary = ' '.join(summary_sentences)
print(summary)

while running this code it's showing this error:

Traceback (most recent call last):
  File "flasexam.py", line 46, in <module>
    sentence_scores[sent] = word_freq[word]
KeyError: 'it'

i am not sure what is the error exactly and how to solve this error.

Replace word_freq[word] by:

if word in word_freq:
    word_freq[word] ...

Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary .

In [8]: a = {"name":"Daka", "sex":"male"}

In [9]: a["name"]
Out[9]: 'Daka'

In [10]: a["name_bla"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-10-91fb451c1e47> in <module>()
----> 1 a["name_bla"]

KeyError: 'name_bla'

Simply put - you're looking for a key 'it' which is not in your dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM