我對Python比較瞭解,所以如果這是一些愚蠢的問題,請耐心等待,但我無法自己弄清楚。我也很高興指出以前有關我可能錯過的問題的提問。python - matplotlib - 將文件內容讀入plot中
所以,我的文件的內容如下:
file.txt的
N 38668442 0.32%
V 14008521 0.12%
ADJ 16112215 0.13%
N 375644830 3.13%
V 380340512 3.17%
ADJ 438651326 3.66%
N 691647661 5.77%
V 832219601 6.94%
ADJ 540782210 4.51%
我喜歡使用matplotlib用下面的代碼把file.txt的的比例成圖(摘錄):
import numpy as np
import matplotlib.pyplot as plt
# data to plot
n_groups = 3
N = (0.32, 3.13, 5.77)
V = (0.12, 3.17, 6.94)
ADJ = (0.13, 3.66, 4.51)
# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.25
opacity = 0.7
rects1 = plt.bar(index, N, bar_width,
alpha=opacity,
color='darkred',
label='N')
rects2 = plt.bar(index + bar_width, V, bar_width,
alpha=opacity,
color='green',
label='V')
rects3 = plt.bar(index + bar_width + bar_width, ADJ, bar_width,
alpha=opacity,
color='darkblue',
label='ADJ')
plt.xlabel('Category')
plt.ylabel('Percentage')
plt.xticks(index + bar_width + bar_width + bar_width + bar_width, ('1.5', '2', '2.5'))
plt.ylim(0, 100)
plt.tight_layout()
plt.show()
在這段代碼中,N,V和ADJ都是元組。所以,我想從file.txt中讀取百分比(沒有百分比符號)成爲一個元組,然後可以用它來生成繪圖(而不是爲N,V,ADJ手動輸入值)。
我設法從文件創建元組,但不幸的是,如果我使用我生成的元組,會引發錯誤消息。元組之間有什麼區別?我錯過了什麼或誤解?從file.txt的
with open('file.txt', 'r') as f:
N_lines = []
V_lines = []
ADJ_lines = []
for line in f:
if line.startswith("N"):
line = line.strip()
line = line[:-1]
parts = line.split("\t")
N_lines.append(parts[2])
if line.startswith("V"):
line = line.strip()
line = line[:-1]
parts = line.split("\t")
V_lines.append(parts[2])
if line.startswith("ADJ"):
line = line.strip()
line = line[:-1]
parts = line.split("\t")
ADJ_lines.append(parts[2])
N = tuple(N_lines)
V = tuple(V_lines)
ADJ = tuple(ADJ_lines)
生成的元組
代碼另外,我印我的元組,他們會略有不同的行情是圍繞項目,所以我試圖刪除它們。
我非常感謝任何幫助或建議!
什麼是錯誤信息? –
TypeError:不支持的操作數類型爲+:'int'和'str' –