有什么方法可以将txt文件列表(带有拆分的行)合并到数据帧中?

2024-09-27 19:28:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一堆txt假新闻文本文件,我想把它们放在熊猫数据框中。但是,在单个文本文件中,第一行和第三行是分开的,这对于所有csv文件都是一样的。但是,我希望他们在熊猫数据帧中进行简单的数据操作。我试着跟踪我的数据:

cols, vals = zip(*[line.split('\n') for line in StringIO("biz01.fake.txt").read().split('\n\n')])
s = pd.Series(vals, cols)
s.index = [s.groupby(level=0).cumcount(), s.index]
s.unstack()

但我犯了一个错误,我不明白为什么。你知道吗

ValueError: not enough values to unpack (expected 2, got 1)

有人能帮我怎么做到吗?有什么解决办法吗?你知道吗

我的原始数据如下:

input txt files

下面是txt文件列表(在我的本地驱动器上)的样子: list of txt files

所需输出示例

1   first_row     second_row
2   headers_1     some text
3   headers_2     some texts

我在flies上放了一些示例文本文件。有人能帮我怎么做吗?你知道吗?你知道吗

新更新

当我尝试以下解决方案时,得到了这种类型的输出:

new output

在我的输入txt文件中,第二行是一个很长的文本,我只需要两列的dataframe和默认的列名。有更好的主意吗?你知道吗


Tags: 文件数据txt示例indexlinesomefiles
1条回答
网友
1楼 · 发布于 2024-09-27 19:28:53

可以使用pandas读入文件,然后删除空行。你知道吗

例如,这里有一个文本文件新闻.txt““

Alex Jones Vindicated in "Pizzagate" Controversy

"Alex Jones, purveyor of the independent investigative news website Infowars and host of The Alex Jones Show, has been vindicated in his claims regarding the so-called "Pizzagate" controversy. Jones and others uncovered evidence last year that top Democratic Party officials were involved in a bizarre, satanic child sex cult and pornography ring using the Washington D.C. pizza parlor Comet Ping Pong Pizza as a front. The allegations rocked the Democratic Party and may have caused serious damage to the Hillary Clinton presidential campaign. Top U.S. federal investigators have now confirmed that they have verified many of these claims after executing raids on the offices of several of the key players. Charges are expected to be filed in the coming days. The news comes as a welcome vindication for Jones, who has been accused by many mainstream media outlets of being a conspiracy theorist and of publishing "fake news". Mr. Jones has often drawn controversy, and was scapegoated in media reports as an example of how inaccurate and misleading news proliferated on social media websites like Facebook, Youtube and Twitter during the 2016 election. Jones has also exposed inconsistencies in the official government accounts of the 9/11 terrorist attacks and the Sandy Hook school shooting in Newtown Connecticut."

然后我用密码

df = pd.read_csv('news.txt', header = None, sep = '\n', skip_blank_lines = True)
#df.dropna(axis = 0, how = 'all', inplace = True)
df = df.T
df.columns = ['Header', 'Rows']

哪些输出

                                              Header    Rows
0   Alex Jones Vindicated in "Pizzagate" Controversy    Alex Jones, purveyor of the independent invest...

相关问题 更多 >

    热门问题