如何在python中从.txt文件中读取数据帧中的大文本文件



我有一个很大的文本文件,里面有几个不同的人的名字和很长的陈述段落。文件格式是。txt,我试图将名称和语句分离到数据框架的两个不同列中。

数据是这种格式-

Harvey: I’m inclined to give you a shot. But what if I decide to go the other way?
Mike: I’d say that’s fair. Sometimes I like to hang out with people who aren’t that bright, you know, just to see how the other half lives.
Mike in the club
(mike speaking to jessica.)
Jessica: How are you mike?
Mike: good!
.....
....

等等

文本文件的长度是400万。

在输出中,我需要一个数据框,其中一个名称列包含发言者的名称,另一个语句列包含该发言者各自的语句。

如果:格式总是"name: one-line -no-colon">
您可以尝试:
df = pd.read_csv('untitled.txt',sep=': ', header=None)

或手动:

f = open("untitled.txt", "r")
file_contents = []
current_name = ""
current_dialogue = ""
for line in f:
splitted_line = line.split(": ")
if len(splitted_line) > 1:
# you are on a row with name: on it
# first stop the current dialogue - save it
if current_name:
file_contents.append([current_name, current_dialogue])
# then update the name encountered
current_name = splitted_line.pop(0)
current_dialogue = ""
current_dialogue += ": ".join(splitted_line)    
# add the last dialogue line
file_contents.append([current_name, current_dialogue])
f.close()
df = pd.DataFrame(file_contents)
df

如果您逐行读取文件,则可以使用类似于这样的代码将说话者从语音文本中分离出来,而无需使用regex。

def find_speaker_and_text_from_line(line):
split = line.split(": ")
name = split.pop(0)
rest = ": ".join(split)
return name, rest

最新更新