[英]How would I add columns from tab separated txt file onto existing pandas dataframe
[英]How can I add sentences from a .txt file to a pandas dataframe?
我正在尝试读取一个 .txt 文件,用句子将其分开,然后创建一个 Pandas 数据框,其中每一行都有一个句子。 输出将是:
0 "blah blah, blah."
1 "more blah."
2 "more more, blah."
到目前为止,我的代码按句子分隔 .txt 文件,但我似乎无法弄清楚如何获取每个句子并将其附加到 Pandas 数据帧。
import os
import sys
import pandas as pd
import re
with open('path/to/file.txt', 'r') as file:
for line in file:
for l in re.split(r"(\.)",line):
string += l
string += '\n'
假设您有一个循环返回string
作为句子的列表对象,如下所示:
["blah blah, blah.", "more blah.", "more more, blah."]
那么你只需要:
pd.DataFrame(string)
但是你的循环看起来像是在每行的基础上拆分句子,而不是跨行。 如果需要跨行捕获句子,则应该这样做:
string = []
with open("path/to/file.txt", "r") as f:
full_text = f.read()
for l in re.split(r"(\.)", full_text):
if l != ".":
string.append(l + "\n")
pd.DataFrame(string)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.