取决于你如何获取数据,我的意思是,如果你得到一个唯一的原始字符串,其中包含来自两个发言者的所有消息,或者你分别从每个发言者那里获取消息。
一种基本方法是建立字符串“speaker X:”(其中 N 是扬声器编号)作为第一个扬声器的扬声器标签,然后您可以使用 NLTK 和/或内置工具从每个扬声器中提取每条消息-in 函数,如 find()。
注意:当我谈论标签时,我指的是一些表达式,可以让我们确定消息是否来自某个说话者。
示例:
你会得到包含演讲者所有干预的整个文本。
1) 设置所有发言者标签以区分他们在整个文本中的干预。
示例:第一个扬声器的扬声器标签可以是“扬声器 1:”
2) 使用 str.find("speaker_tag") 查找说话者的所有干预
3) 将每个说话者的所有干预添加到不同的数据结构中。
我认为演讲者的干预列表可能很有用,然后如果您想再次在一条短信中获得所有这些干预,您可以使用
一些内置函数,如 str.join() 将它们再次连接成一个字符串。
解决这个问题的其他选择是使用像 NLTK 这样的工具(我认为这个工具非常适合对文本进行分类)
它具有非常有用的功能,例如标记化,我认为这对解决您的问题很有用。
在下面的示例中,我将使用 find() 和切片作为文本标记化的基本示例:
文本数据:
text = "speaker 1: hello everyone, I am Thomas speaker 2: Hello friends, I am John speaker 1: How are you? I am great being here speaker 2: It's the same for me"
代码示例:
from itertools import islice, tee
FIRST_SPEAKER_TAG = "speaker 1:"
SECOND_SPEAKER_TAG = "speaker 2:"
def get_speaker_positions(text, speaker_tag):
total_interventions = text.count(speaker_tag)
positions = []
position = 0
for i in range(total_interventions):
positions.append(text.find(speaker_tag, position))
# we increase the position by the addition of all the previous
# positions to reach the following occurrences through the list of
# positions
position += sum(positions) + 1
return positions
def slices(iterable, n):
return zip(*(islice(it, i, None) for i, it in enumerate(tee(iterable, n))))
def get_text_interventions(text, speaker_tags):
# speakers' interventions of the text
interventions = { speaker_tag: "" for speaker_tag in speaker_tags }
# positions where start each intervention in the text
# (the last one is used to get the rest of the text, because it's the
# last intervention)
# (we need to sort the positions to get the interventions in the correct
# order)
speaker_positions = [
get_speaker_positions(text, speaker) for speaker in speaker_tags
]
all_positions = [
position for sublist in speaker_positions for position in sublist
]
all_positions.append(len(text))
all_positions.sort()
# generate the list of pairs that match a certain intervention
# the pairs are formed by the initial and the end position of the
# intervention
text_chunks = list(slices(all_positions, 2))
for chunk in text_chunks:
# we assign the intervention according to which
# list of speaker interventions the position exists
# when slicing we add the speaker tag's length to exclude
# the speaker tag from the own intervention
if chunk[0] in speaker_positions[0]:
intervention = text[chunk[0]+len(speaker_tags[0]):chunk[1]]
interventions[speaker_tags[0]] += intervention
elif chunk[0] in speaker_positions[1]:
intervention = text[chunk[0]+len(speaker_tags[1]):chunk[1]]
interventions[speaker_tags[1]] += intervention
return interventions
text_interventions = get_text_interventions(text, [ FIRST_SPEAKER_TAG, SECOND_SPEAKER_TAG ])
注意事项:
如果您有任何疑问,可以阅读 itertools 文档中的更多详细信息:
- 有关 itertools.islice 和 itertools.tee 的文档:
islice
tee
如果您对该示例有任何不明白的地方,请随时问我。
希望对你有帮助! =)