【发布时间】:2022-01-14 06:42:41
【问题描述】:
我有几个文本文件,我想按段落拆分并转置为 csv 文件。我的文本文件中的每个段落都由一个空行分隔,有些长段落有几行。这是一个文本文件的示例:
“世界你好!
布拉布拉
(空行)
这是第二段。 这里有更多文字
这是一个很长的段落。”
我想获取以下 csv 文件:
| filename | text |
|---|---|
| 1.txt | Hello world! Blabla |
| 1.txt | This is the 2nd paragrah. Here is more text and this is a very long paragraph. |
这是我目前的代码,但它只提供了一行:"1.text, [""Hello world!"", ""This is the 2nd paragraph. Here is more text. \nand这是一个很长的段落""]":
import os, csv
os.chdir('path where I have text files')
from pathlib import Path
with open('output.csv', 'w', newline="", encoding="utf-16") as out_file:
csv_out = csv.writer(out_file)
csv_out.writerow(['filename', 'Content'])
for fileName in Path('.').glob('*.txt'):
csv_out.writerow([str(fileName),open(str(fileName.absolute())).read().strip().split("\n\n")])
【问题讨论】:
-
paragraph是什么意思?新队?你从当前代码中得到了什么输出? -
不要简单地报告“它不起作用”,请始终说明您获得的结果与您的预期。
-
请详细说明为什么您会在 pandas
dataframe中阅读它们。您可以添加预处理步骤以使用单个\n删除多个连续的(\n){1,}。
标签: python csv text split paragraph