Danh sách các từ đầu ra phổ biến nhất được đưa ra dưới đây:
[['Phim', 904], ['Phim', 561], ['One', 379], ['Like', 292]]]]]
Tôi muốn một biểu đồ bằng cách sử dụng matplotlib cho mỗi từ theo các số
làm ơn giúp tôi
Sid
5525 Huy hiệu bạc21 Huy hiệu Đồng5 silver badges21 bronze badges
Hỏi ngày 6 tháng 8 năm 2016 lúc 14:29Aug 6, 2016 at 14:29
4
Dưới đây là một thông qua nhanh chóng của ví dụ này bằng cách sử dụng biểu đồ thanh.
#!/usr/bin/env python
# a bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt
data = [['film', 904], ['movie', 561], ['one', 379], ['like', 292]]
names, values = zip[*data] # @comment by Matthias
# names = [x[0] for x in data] # These two lines are equivalent to the the zip-command.
# values = [x[1] for x in data] # These two lines are equivalent to the the zip-command.
ind = np.arange[len[data]] # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots[]
rects1 = ax.bar[ind, values, width, color='r']
# add some text for labels, title and axes ticks
ax.set_ylabel['Count']
ax.set_xticks[ind+width/2.]
ax.set_xticklabels[names]
def autolabel[rects]:
# attach some text labels
for rect in rects:
height = rect.get_height[]
ax.text[rect.get_x[] + rect.get_width[]/2., 1.05*height,
'%d' % int[height],
ha='center', va='bottom']
autolabel[rects1]
plt.show[]
Đã trả lời ngày 6 tháng 8 năm 2016 lúc 14:45Aug 6, 2016 at 14:45
PathorenPathorenpathoren
1.6242 Huy hiệu vàng14 Huy hiệu bạc22 Huy hiệu đồng2 gold badges14 silver badges22 bronze badges
4
Bạn có thể thử điều này:
"""
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt
data = [['film', 904], ['movie', 561], ['one', 379], ['like', 292]]
n_groups = len[data]
vals_films = [x[1] for x in data]
legends_films = [x[0] for x in data]
fig, ax = plt.subplots[]
index = np.arange[n_groups]
bar_width = 0.25
opacity = 0.4
rects1 = plt.bar[index, vals_films, bar_width,
alpha=opacity,
color='b',
label='Ocurrences']
plt.xlabel['Occurrences']
plt.ylabel['Words']
plt.title['Occurrences by word']
plt.xticks[index + bar_width, legends_films]
plt.legend[]
plt.tight_layout[]
plt.show[]
Nếu bạn tình cờ sử dụng Notebook Jupyter [rất được khuyến khích], hãy thêm nó vào đầu sổ ghi chép: %matplotlib notebook
Đã trả lời ngày 6 tháng 8 năm 2016 lúc 14:44Aug 6, 2016 at 14:44
Pablo Santa Cruzpablo Santa CruzPablo Santa Cruz
172K32 Huy hiệu vàng238 Huy hiệu bạc290 Huy hiệu Đồng32 gold badges238 silver badges290 bronze badges
1
Tổng quan
Giảng dạy: 0 phút Bài tập: 0 phút 0 min
Exercises: 0 minCâu hỏi
Làm thế nào tôi có thể vẽ phân phối tần số của các từ thường xuyên nhất trong một bộ sưu tập?
Làm thế nào tôi có thể trực quan hóa dữ liệu này dưới dạng đám mây từ.
Mục tiêu
Tìm hiểu cách vẽ phân phối tần số của mã thông báo trong văn bản.
Tìm hiểu cách tạo một đám mây từ hiển thị các từ thường xuyên nhất trong văn bản.
Trực quan hóa phân phối tần số của mã thông báo trong văn bản
Đồ thị
Phương pháp plot[]
có thể được gọi để vẽ phân phối tần số dưới dạng biểu đồ cho các mã thông báo phổ biến nhất trong văn bản.
fdist.plot[30,title='Frequency distribution for 30 most common tokens in our text collection']
Bạn có thể thấy rằng bản phân phối chứa rất nhiều từ không nội dung như là The The The The, một trong những từ, chúng tôi gọi các từ dừng này] và dấu câu. Chúng ta có thể loại bỏ chúng trước khi vẽ đồ thị. Chúng tôi cần nhập
"""
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt
data = [['film', 904], ['movie', 561], ['one', 379], ['like', 292]]
n_groups = len[data]
vals_films = [x[1] for x in data]
legends_films = [x[0] for x in data]
fig, ax = plt.subplots[]
index = np.arange[n_groups]
bar_width = 0.25
opacity = 0.4
rects1 = plt.bar[index, vals_films, bar_width,
alpha=opacity,
color='b',
label='Ocurrences']
plt.xlabel['Occurrences']
plt.ylabel['Words']
plt.title['Occurrences by word']
plt.xticks[index + bar_width, legends_films]
plt.legend[]
plt.tight_layout[]
plt.show[]
0 từ gói """
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt
data = [['film', 904], ['movie', 561], ['one', 379], ['like', 292]]
n_groups = len[data]
vals_films = [x[1] for x in data]
legends_films = [x[0] for x in data]
fig, ax = plt.subplots[]
index = np.arange[n_groups]
bar_width = 0.25
opacity = 0.4
rects1 = plt.bar[index, vals_films, bar_width,
alpha=opacity,
color='b',
label='Ocurrences']
plt.xlabel['Occurrences']
plt.ylabel['Words']
plt.title['Occurrences by word']
plt.xticks[index + bar_width, legends_films]
plt.legend[]
plt.tight_layout[]
plt.show[]
1 để làm điều này. Danh sách các từ dừng được kết hợp với danh sách dấu câu và danh sách các chữ số đơn bằng cách sử dụng các dấu hiệu """
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt
data = [['film', 904], ['movie', 561], ['one', 379], ['like', 292]]
n_groups = len[data]
vals_films = [x[1] for x in data]
legends_films = [x[0] for x in data]
fig, ax = plt.subplots[]
index = np.arange[n_groups]
bar_width = 0.25
opacity = 0.4
rects1 = plt.bar[index, vals_films, bar_width,
alpha=opacity,
color='b',
label='Ocurrences']
plt.xlabel['Occurrences']
plt.ylabel['Words']
plt.title['Occurrences by word']
plt.xticks[index + bar_width, legends_films]
plt.legend[]
plt.tight_layout[]
plt.show[]
2 vào danh sách các mục mới sẽ bị bỏ qua.nltk.download['stopwords']
from nltk.corpus import stopwords
remove_these = set[stopwords.words['english'] + list[string.punctuation] + list[string.digits]]
filtered_text = [w for w in lower_india_tokens if not w in remove_these]
fdist_filtered = FreqDist[filtered_text]
fdist_filtered.plot[30,title='Frequency distribution for 30 most common tokens in our text collection [excluding stopwords and punctuation]']
Ghi chú
Mặc dù có ý nghĩa khi loại bỏ các từ dừng cho loại phân tích tần số này, điều cần thiết là giữ chúng trong dữ liệu cho các tác vụ phân tích văn bản khác. Việc giữ lại văn bản gốc là rất quan trọng, ví dụ, khi lấy các thẻ một phần của văn bản hoặc để nhận dạng tên trong một văn bản. Chúng tôi sẽ xem xét các loại xử lý văn bản trong ngày 2 của khóa học này.
Word Cloud
Chúng tôi cũng có thể trình bày các mã thông báo được lọc dưới dạng đám mây từ. Điều này cho phép chúng tôi có một cái nhìn tổng quan về kho văn bản bằng phương pháp
"""
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt
data = [['film', 904], ['movie', 561], ['one', 379], ['like', 292]]
n_groups = len[data]
vals_films = [x[1] for x in data]
legends_films = [x[0] for x in data]
fig, ax = plt.subplots[]
index = np.arange[n_groups]
bar_width = 0.25
opacity = 0.4
rects1 = plt.bar[index, vals_films, bar_width,
alpha=opacity,
color='b',
label='Ocurrences']
plt.xlabel['Occurrences']
plt.ylabel['Words']
plt.title['Occurrences by word']
plt.xticks[index + bar_width, legends_films]
plt.legend[]
plt.tight_layout[]
plt.show[]
3. Đầu vào cho phương pháp này là một từ điển tần số của tất cả các mã thông báo và số lượng của chúng trong văn bản. Điều này cần được tạo trước tiên bằng cách nhập gói """
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt
data = [['film', 904], ['movie', 561], ['one', 379], ['like', 292]]
n_groups = len[data]
vals_films = [x[1] for x in data]
legends_films = [x[0] for x in data]
fig, ax = plt.subplots[]
index = np.arange[n_groups]
bar_width = 0.25
opacity = 0.4
rects1 = plt.bar[index, vals_films, bar_width,
alpha=opacity,
color='b',
label='Ocurrences']
plt.xlabel['Occurrences']
plt.ylabel['Words']
plt.title['Occurrences by word']
plt.xticks[index + bar_width, legends_films]
plt.legend[]
plt.tight_layout[]
plt.show[]
4 trong Python và tạo từ điển bằng cách sử dụng biến """
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt
data = [['film', 904], ['movie', 561], ['one', 379], ['like', 292]]
n_groups = len[data]
vals_films = [x[1] for x in data]
legends_films = [x[0] for x in data]
fig, ax = plt.subplots[]
index = np.arange[n_groups]
bar_width = 0.25
opacity = 0.4
rects1 = plt.bar[index, vals_films, bar_width,
alpha=opacity,
color='b',
label='Ocurrences']
plt.xlabel['Occurrences']
plt.ylabel['Words']
plt.title['Occurrences by word']
plt.xticks[index + bar_width, legends_films]
plt.legend[]
plt.tight_layout[]
plt.show[]
5 làm đầu vào.Chúng tôi tạo ra WordCloud bằng từ điển tần số và vẽ hình con số thành kích thước. Chúng ta có thể hiển thị cốt truyện bằng cách sử dụng
"""
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt
data = [['film', 904], ['movie', 561], ['one', 379], ['like', 292]]
n_groups = len[data]
vals_films = [x[1] for x in data]
legends_films = [x[0] for x in data]
fig, ax = plt.subplots[]
index = np.arange[n_groups]
bar_width = 0.25
opacity = 0.4
rects1 = plt.bar[index, vals_films, bar_width,
alpha=opacity,
color='b',
label='Ocurrences']
plt.xlabel['Occurrences']
plt.ylabel['Words']
plt.title['Occurrences by word']
plt.xticks[index + bar_width, legends_films]
plt.legend[]
plt.tight_layout[]
plt.show[]
6.from collections import Counter
dictionary=Counter[filtered_text]
import matplotlib.pyplot as plt
from wordcloud import WordCloud
cloud = WordCloud[max_font_size=80,colormap="hsv"].generate_from_frequencies[dictionary]
plt.figure[figsize=[16,12]]
plt.imshow[cloud, interpolation='bilinear']
plt.axis['off']
plt.show[]s
Đám mây từ hình
Và bây giờ là một đám mây từ có hình cho một chút thú vị, nếu có thời gian vào cuối ngày 1. Điều này sẽ trình bày công việc của bạn trong hình dạng của một hình ảnh nhất định.
Bạn cần một tệp hình dạng mà chúng tôi cung cấp cho bạn dưới dạng biểu tượng y tế:
Hình ảnh mặt nạ cần có nền trong suốt để chỉ có hình dạng màu đen được sử dụng làm mặt nạ cho đám mây từ.
Để hiển thị đám mây từ có hình, bạn cần nhập gói
"""
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt
data = [['film', 904], ['movie', 561], ['one', 379], ['like', 292]]
n_groups = len[data]
vals_films = [x[1] for x in data]
legends_films = [x[0] for x in data]
fig, ax = plt.subplots[]
index = np.arange[n_groups]
bar_width = 0.25
opacity = 0.4
rects1 = plt.bar[index, vals_films, bar_width,
alpha=opacity,
color='b',
label='Ocurrences']
plt.xlabel['Occurrences']
plt.ylabel['Words']
plt.title['Occurrences by word']
plt.xticks[index + bar_width, legends_films]
plt.legend[]
plt.tight_layout[]
plt.show[]
7 """
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt
data = [['film', 904], ['movie', 561], ['one', 379], ['like', 292]]
n_groups = len[data]
vals_films = [x[1] for x in data]
legends_films = [x[0] for x in data]
fig, ax = plt.subplots[]
index = np.arange[n_groups]
bar_width = 0.25
opacity = 0.4
rects1 = plt.bar[index, vals_films, bar_width,
alpha=opacity,
color='b',
label='Ocurrences']
plt.xlabel['Occurrences']
plt.ylabel['Words']
plt.title['Occurrences by word']
plt.xticks[index + bar_width, legends_films]
plt.legend[]
plt.tight_layout[]
plt.show[]
8 cũng như """
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt
data = [['film', 904], ['movie', 561], ['one', 379], ['like', 292]]
n_groups = len[data]
vals_films = [x[1] for x in data]
legends_films = [x[0] for x in data]
fig, ax = plt.subplots[]
index = np.arange[n_groups]
bar_width = 0.25
opacity = 0.4
rects1 = plt.bar[index, vals_films, bar_width,
alpha=opacity,
color='b',
label='Ocurrences']
plt.xlabel['Occurrences']
plt.ylabel['Words']
plt.title['Occurrences by word']
plt.xticks[index + bar_width, legends_films]
plt.legend[]
plt.tight_layout[]
plt.show[]
9. Hình ảnh trước tiên cần được mở và chuyển đổi thành một mảng numpy mà chúng ta gọi là fdist.plot[30,title='Frequency distribution for 30 most common tokens in our text collection']
0. Một bản đồ màu tùy chỉnh [fdist.plot[30,title='Frequency distribution for 30 most common tokens in our text collection']
1] được tạo để trình bày các từ trong phông chữ đen. Sau đó, đám mây từ được tạo bằng nền trắng, mặt nạ và bản đồ màu được đặt làm tham số và được tạo từ từ điển chứa số lần xuất hiện cho mỗi từ.from PIL import Image
import numpy as np
med_mask = np.array[Image.open["medical.png"]]
# Custom Colormap
from matplotlib.colors import LinearSegmentedColormap
colors = ["#000000", "#111111", "#101010", "#121212", "#212121", "#222222"]
cmap = LinearSegmentedColormap.from_list["mycmap", colors]
wc = WordCloud[background_color="white", mask=med_mask, colormap=cmap]
wc.generate_from_frequencies[dictionary]
plt.figure[figsize=[16,12]]
plt.imshow[wc, interpolation="bilinear"]
plt.axis["off"]
Nhiệm vụ 1: Lọc phân phối tần số thêm
Thay đổi biểu đồ phân phối tần số cuối cùng để không hiển thị bất kỳ chuỗi nào sau đây: Thời gian ,, Cân nhắc thêm chúng vào danh sách
2. Gợi ý: Bạn có thể tạo một danh sách các chuỗi của tất cả các số trong khoảng từ 0 đến 10000000 bằng cách gọifdist.plot[30,title='Frequency distribution for 30 most common tokens in our text collection']
3fdist.plot[30,title='Frequency distribution for 30 most common tokens in our text collection']
Câu trả lời
numbers=list[map[str, range[0,1000000]]] otherTokens=["..."] remove_these = set[stopwords.words['english'] + list[string.punctuation] + numbers + otherTokens] filtered_text = [w for w in lower_india_tokens if not w in remove_these] fdist_filtered = FreqDist[filtered_text_new] fdist_filtered.plot[30,title='Frequency distribution for 30 most common tokens in our text collection [excluding stopwords, punctuation, numbers etc.]']
Nhiệm vụ 2: Redraw Word Cloud
Vua lại từ đám mây từ với biến
5 được cập nhật [sau khi xóa các chuỗi trong Task 1].""" Bar chart demo with pairs of bars grouped for easy comparison. """ import numpy as np import matplotlib.pyplot as plt data = [['film', 904], ['movie', 561], ['one', 379], ['like', 292]] n_groups = len[data] vals_films = [x[1] for x in data] legends_films = [x[0] for x in data] fig, ax = plt.subplots[] index = np.arange[n_groups] bar_width = 0.25 opacity = 0.4 rects1 = plt.bar[index, vals_films, bar_width, alpha=opacity, color='b', label='Ocurrences'] plt.xlabel['Occurrences'] plt.ylabel['Words'] plt.title['Occurrences by word'] plt.xticks[index + bar_width, legends_films] plt.legend[] plt.tight_layout[] plt.show[]
Câu trả lời
dictionary=Counter[filtered_text] import matplotlib.pyplot as plt from wordcloud import WordCloud cloud = WordCloud[max_font_size=80,colormap="hsv"].generate_from_frequencies[dictionary] plt.figure[figsize=[16,12]] plt.imshow[cloud, interpolation='bilinear'] plt.axis['off'] plt.show[]
Nhiệm vụ 2: Redraw Word Cloud
Vua lại từ đám mây từ với biến
5 được cập nhật [sau khi xóa các chuỗi trong Task 1].""" Bar chart demo with pairs of bars grouped for easy comparison. """ import numpy as np import matplotlib.pyplot as plt data = [['film', 904], ['movie', 561], ['one', 379], ['like', 292]] n_groups = len[data] vals_films = [x[1] for x in data] legends_films = [x[0] for x in data] fig, ax = plt.subplots[] index = np.arange[n_groups] bar_width = 0.25 opacity = 0.4 rects1 = plt.bar[index, vals_films, bar_width, alpha=opacity, color='b', label='Ocurrences'] plt.xlabel['Occurrences'] plt.ylabel['Words'] plt.title['Occurrences by word'] plt.xticks[index + bar_width, legends_films] plt.legend[] plt.tight_layout[] plt.show[]
Những điểm chính
Phân phối tần số có thể được tạo bằng phương pháp
plot[]
.