python - Plotly:从 csv 中按年份绘制用户输入的词频

标签 python python-3.x plotly

我想绘制用户输入中单词随时间变化的单词使用情况。例如。用户输入“begab,social,demokrat”。这些术语存储在变量u_input中。我想使用 startswith() 方法在使用术语“social”等时包含“social、socialismus、socialreform”等词。

作为准备工作,我将历史普鲁士报纸语料库的 2300 个 xml 文件合并到 csv 文件中,其中包含有关“年份、字数、计数”的信息:

year| word        | count
----|-------------|----
1864|befürchtete  |1
1864|befürchtungen|1
1864|begab        |1
1864|begab        |2
1864|begab        |3
1864|begab        |5
1864|begaben      |1
1864|begaben      |3
1865|begab        |2
1865|begab        |2

然后,我使用 Pandas 对数据进行分组,以便获得每年的单词总数,并将数据保存为新的 csv 文件“pandas_dict.csv”:

year| word        | count
----|-------------|----
1864|befürchtete  |1
1864|befürchtungen|1
1864|begab        |11
1864|begaben      |4
1865|begab        |4

我现在想使用plotly(离线)绘制一个图,显示示例术语“social、conserv、kommuni”的单词使用图。 (原因:在这个例子中,我想比较报纸对社会党、保守派和共产主义者的报道,更具体地说,与政党相关的词语的普遍突出程度,因此所有“社会”或“共产主义”。 )

不幸的是,我读到的所有示例中的代码都不起作用,因为我找到的所有示例中都没有包含任何类型的机制来仅显示 u_input 中的术语的图表。

import plotly as py
import plotly.graph_objs as go
import pandas as pd

# Create DataFrame from prepared csv
df = pd.read_csv(self.dir + self.dict_dir + 'pandas_dict.csv', header=None, names=['year', 'word', 'count'])
# define data for plotting - how do I incorporate u_input?
trace1 = go.Scatter(x=df['year'], y=df['count'], mode='lines', name='test')

layout = go.Layout(title='Word usage over time', plot_bgcolor='rgb(230, 230,230)')
fig = go.Figure(data=[trace1], layout=layout)

# Plot data
py.offline.plot(fig)

这是我用 NLTK 创建的一个旧示例,它大致显示了我想用plotly 做什么: word usage over time in american inaugural speeches

最佳答案

  • 您可以首先通过 contains 过滤数据帧中的每个单词(df[df['word'].str.contains(word)]
  • 接下来通过 groupby 按年份对所有内容进行分组
  • 最终仅报告“count”并对其求和 (['count'].aggregate(sum))
  • 为了绘制它,请迭代 u_input 中的单词并为每个单词添加跟踪,
<小时/>
import pandas as pd
import plotly
import io

txt="""year|word|count
1864|befürchtete|1
1864|befürchtungen|1
1864|begab|11
1864|begaben|4
1865|begab|4
1864|kommuni|3
1864|social|2
1864|conserv|5
1865|kommuni|6
1865|social|3
1865|conserv|4
1866|kommuni|8
1866|social|2
1866|conserv|6
1867|conservativ|4
1867|conservative|1
1867|socialist|1
1867|socialisti|2
1867|nonsense|99
1867|kommunist|4
1867|kommuni|2
"""

u_input = ['kommuni', 'social', 'conserv']

df = pd.read_csv(io.StringIO(txt), sep='|')

#filter the dataframe according to u_input
df = df[df['word'].str.contains('|'.join(u_input))]

traces = [plotly.graph_objs.Scatter(x=df['year'][df['word'].str.contains(word)],
                                    y=df[df['word'].str.contains(word)].groupby(['year'])['count'].aggregate(sum),
                                    name=word, mode='lines') for word in u_input]

layout = plotly.graph_objs.Layout(xaxis=dict(tickvals=df['year'].unique()))
fig = plotly.graph_objs.Figure(data=traces, layout=layout)
plotly.offline.plot(fig)

关于python - Plotly:从 csv 中按年份绘制用户输入的词频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42858066/

相关文章:

python - 给定列表中指定项目的位置,逐渐将一个添加到索引列表

python - 如何深度复制具有包装函数的对象?

python - 导入外部/主目录时,Python 中出现“无模块命名”错误

python - 如何使用Python在终端中自动输入问题的多行答案?

python - 如何使用类外部的函数作为类内部的属性?

python-3.x - 当列数未知时,替换 Pandas Dataframe 中特定列中的值

python - 如何从经/纬度坐标计算形状并用绘图绘制它

python - 查找两个日期之间的对象 TinyDB

python - 在 plotly 中更改分组条形图的组内顺序

python - 如何使用 matplotlib 或 plotly 在 3-D 曲面图上叠加等高线图?