我在Coursera上做了一个作业并成功通过。我在Jupyter notebook上编译并得到了准确的结果。https://poskzjbvcahynihgdhljpw.coursera-apps.org/notebooks/C1M6L2_Final_Project_V3.ipynb
我在我的pycharm上输入了类似的代码:
但我得到了一个错误:
import wordcloud
import numpy as np
from matplotlib import pyplot as plt
from IPython.display import display
import fileupload
import io
import sys
# This is the uploader widget
def _upload():
_upload_widget = fileupload.FileUploadWidget()
def _cb(change):
global file_contents
decoded = io.StringIO(change['owner'].data.decode('utf-8'))
filename = change['owner'].filename
print('Uploaded `{}` ({:.2f} kB)'.format(
filename, len(decoded.read()) / 2 **10))
file_contents = decoded.getvalue()
_upload_widget.observe(_cb, names='data')
display(_upload_widget)
_upload()
def calculate_frequencies(file_contents):
# Here is a list of punctuations and uninteresting words,use to process the 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"]
count_frequency = {}
for contents in file_contents:
if (contents not in punctuations) and (contents not in uninteresting_words):
if contents not in count_frequency:
count_frequency[contents] = 1
else:
count_frequency[contents] += 1
# wordcloud
cloud = wordcloud.WordCloud()
cloud.generate_from_frequencies(count_frequency)
return cloud.to_array()
# Displaying my wordcloud image
myimage = calculate_frequencies(file_contents)
plt.imshow(myimage, interpolation = 'nearest')
plt.axis('off')
plt.show()
Traceback (most recent call last):
File "/home/ashik/PycharmProjects/RawCodes/final_project_google_crash_course_with_python.py", line 54, in <module>
myimage = calculate_frequencies(file_content)
NameError: name 'file_content' is not defined
FileUploadWidget(label='Browse', _dom_classes=('widget_item', 'btn-group'))
Process finished with exit code 1
2条答案
按热度按时间vd2z7a6w1#
执行以下更改:
1.
应修复该问题
oxf4rvwz2#
您需要执行以下步骤:
重要信息!如果这是您第一次运行上面包含安装和导入的单元格,您需要立即保存此笔记本。然后在上面的“文件”菜单下,选择“关闭并暂停”。当笔记本完全关闭后,重新打开它。这是使必要的更改生效的唯一方法。
要上传文本文件,请运行以下单元格,其中包含自定义上传器小部件的所有代码。运行此单元格后,其下方应显示“浏览”按钮。单击此按钮并在窗口中导航,以找到保存的文本文件。