【问题标题】:How do I convert this text to a panda dataframe?如何将此文本转换为熊猫数据框?
【发布时间】:2020-05-09 21:57:58
【问题描述】:

我有一个没有csv格式的文件,内容是这样的。

文件:

"TITULO: Albedo SUBTITULO Y PARRAFO: ===Trees===
Because forests generally have a low albedo, (the majority of the ultraviolet and [[visible 
`spectrum]] is absorbed through [[photosynthesis]])
"

"TITULO: Albedo SUBTITULO Y PARRAFO: ===Human activities===
Human activities (e.g., deforestation, farming, and urbanization) change the albedo of various areas 
around 
"TITULO: Abraham Lincoln SUBTITULO Y PARRAFO: ==U.S. House of Representatives, 1847–1849==
[[File:Abraham Lincoln by Nicholas Shepherd, 1846-crop.jpg|thumb|upright|alt=Middle 
True to his record, Lincoln professed to friends in 1861 to be ""an old line Whig,
"TITULO: Abraham Lincoln SUBTITULO Y PARRAFO: ===Re-election===
{{Main|1864 United States presidential election}}
[[File:ElectoralCollege1864.svg|thumb|upright=1.3|alt=Map of the 
"TITULO: Algeria SUBTITULO Y PARRAFO: ===Research and alternative energy sources===
Algeria has invested an estimated 100 billion dinars towards developing research facilities and 
paying researchers. 
Ecological anthropology is defined as the ""study of [[cultural adaptation]]s to environments""
"TITULO: Agricultural science SUBTITULO Y PARRAFO: ==Fields or related disciplines==
{{Col-begin}}
{{Col-break}}
* [[Agricultural biotechnology]]
* [[Agricultural chemistry]]
* [[Agricultural diversification]]
* [[Agricultural education]]
* [[Agricultural economics]]
* [[Agricultural engineering]]

我有这个程序

import pandas as pd

data = pd.read_csv('datos_titulos.csv', header = None)
print(data)

我有这个错误:

ParserError: Error tokenizing data. C error: Expected 1 fields in line 6, saw 3

数据框表必须是

Tile                   Head                          TXT
Albedo                 Trees                         Because forests generally have a low  ...([[photosynthesis]])
Albedo                 Human activities              Human activities (e.g., de...areas around 
Abraham Lincoln        U.S. House of..1849           [[File:Abraham Lincoln by... line Whig,
.
.
.
Agricultural science  Fields or related disciplines  {{Col-begin}} {{Col-break}}...* [[Agricultural engineering]]

也就是说, 列标题是标题。 头是 párrafo y subtitulo == 这个文本 == txt 是下一个标题的文本。

【问题讨论】:

  • 你能不能使用多个查找来查找标题的一个结尾,另一个查找副标题和段落?或者是更好的正则表达式?

标签: python pandas file dataframe


【解决方案1】:

IIUC,您可以在 re.module 中使用两组正则表达式,首先我们将遍历您的文本文件以获取 title 和 head 字段。

其次,我们将使用re.split 来收集文本字段,这是基于这样的假设:虽然您的数据是杂乱的文本格式,但它仍然保持某种顺序 Title > Header > Text。

您必须进一步清理Text 列,但这只是乐趣的一部分:)

import re
from collections import defaultdict
import pandas as pd

pandas_dict = defaultdict(list)

with open("file.txt", "r") as f:
    for line in f:

      pat = r"TITULO: (.*) SUBTITULO Y PARRAFO: ===(.*?)==="
      if re.search(pat, line):
          pandas_dict["title"].append(re.search(pat, line).group(1))
          pandas_dict["head"].append(re.search(pat, line).group(2))


with open("file.txt", "r") as f:
    body = f.read()

    b = re.split(r"===", body.strip())

    for line in b[2::2]:
        pandas_dict["text"].append(line.strip())

df = pd.DataFrame(pandas_dict)

print(df)

             title                                     head                                               text
0           Albedo                                    Trees  Because forests generally have a low albedo, (...
1           Albedo                         Human activities  Human activities (e.g., deforestation, farming...
2  Abraham Lincoln                              Re-election  {{Main|1864 United States presidential electio...
3          Algeria  Research and alternative energy sources  Algeria has invested an estimated 100 billion ...

print(df[df['Title'] == 'Algeria']['Text'])

paying researchers.
Ecological anthropology is defined as the ""study of [[cultural adaptation]]s to environments""
"TITULO: Agricultural science SUBTITULO Y PARRAFO: ==Fields or related disciplines==
{{Col-begin}}
{{Col-break}}
* [[Agricultural biotechnology]]
* [[Agricultural chemistry]]
* [[Agricultural diversification]]
* [[Agricultural education]]
* [[Agricultural economics]]
* [[Agricultural engineering]]"

【讨论】:

  • 我有一个运行这个程序,但在数据框第 21 行和第 23 行是错误的。 21 安哥拉人口统计 [[总生育率]]:6.09 个孩子/女性(2018 年估计)国家... 22 艾伯塔省 21 世纪 [[文件:东村卡尔加里洪水 2013.jpg|周四... 23 阿尔伯特爱因斯坦 =第二次世界大战和曼哈顿计划 =\n{{另见|爱因斯坦 – Szilá¡rd letter}}
  • @ProSyth 你能链接你的 txt 文件吗?
猜你喜欢
  • 2017-08-27
  • 2015-11-14
  • 1970-01-01
  • 1970-01-01
  • 2013-09-05
  • 2023-03-18
  • 2015-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多