【问题标题】:break paragraph into sentences in python and link back to an ID在python中将段落分成句子并链接回一个ID
【发布时间】:2018-12-29 22:37:44
【问题描述】:

我有两个列表,一个带有 id,一个带有每个 id 对应的 cmets。

list_responseid = ['id1', 'id2', 'id3', 'id4'] 

list_paragraph = [['I like working and helping them reach their goals.'],
 ['The communication is broken.',
  'Information that should have come to me is found out later.'],
 ['Try to promote from within.'],
 ['I would relax the required hours to be available outside.',
  'We work a late night each week.']]

ResponseID“id1”与段落相关(“我喜欢工作并帮助他们实现目标。”)等等。

我可以使用以下函数将段落分成句子:

list_sentence = list(itertools.chain(*list_paragraph))

获取最终结果的语法是什么,即数据框(或列表)具有单独的句子条目并具有与该句子关联的 ID(现在链接到段落)。最终结果将如下所示(最后我会将列表转换为熊猫数据框)。

id1 'I like working with students and helping them reach their goals.'
id2 'The communication from top to bottom is broken.'
id2 'Information that should have come to me is found out later and in some cases students know more about what is going on than we do!'
id3 'Try to promote from within.'
id4 'I would relax the required 10 hours to be available outside of 8 to 5 back to 9 to 5 like it used to be.'
id4 'We work a late night each week and rarely do students take advantage of those extended hours.'

谢谢。

【问题讨论】:

  • 所有这些单元素列表是怎么回事?
  • 当你想要一个像这样的“关联”时,我建议使用像 dict 这样的映射类,所以像 dict(zip(list_responseid, [lp[0] for lp in list_paragraph])) 这样的东西可能会起作用。
  • dict 确实返回了一些结果,但它不完整,它跳过了一些句子。不过感谢您的提示,我会继续寻找。
  • 那么就dict(zip(list_responseid, list_paragraph))
  • 我可以看到,当我删除 0 时,它会显示所有句子。现在,如果我需要它的结构像一个数据框,每个句子有一条记录并与之关联 ID,我需要遍历该字典中的每个值,对吗?

标签: python split sentence


【解决方案1】:

如果你经常这样做,它会更清晰,并且可能更有效,具体取决于数组的大小,如果你用两个常规嵌套循环为此创建一个专用函数,但如果你需要一个快速的内衬(它就是这样做的):

id_sentence_tuples = [(list_responseid[id_list_idx], sentence) for id_list_idx in range(len(list_responseid)) for sentence in list_paragraph[id_list_idx]]

id_sentence_tuples 将是一个元组列表,其中每个元素都是一对像 (paragraph_id, sentence) 一样的结果,就像您期望的那样。 另外,我建议您在执行此操作之前检查两个列表的长度是否相同,以防您没有收到有意义的错误。

if len(list_responseid) != len(list_paragraph):
    IndexError('Lists must have same cardinality')

【讨论】:

  • 谢谢!这正是我一直在寻找的。 '
【解决方案2】:

我有一个带有 ID 和评论的数据框 (col = ['ID','Review'])。如果您可以将这些列表组合成一个数据框,那么您可以使用我的方法。我使用 nltk 将这些评论拆分成句子,然后在循环中链接回 ID。以下是您可以使用的代码。

## Breaking feedback into sentences
import nltk
count = 0
df_sentences = pd.DataFrame()
for index, row in df.iterrows():
    feedback = row['Reviews']
    sent_text = nltk.sent_tokenize(feedback) # this gives us a list of sentences
    for j in range(0,len(sent_text)):
        # print(index, "-", sent_text[j])
        df_sentences = df_sentences.append({'ID':row['ID'],'Count':int(count),'Sentence':sent_text[j]}, ignore_index=True)
        count = count + 1
print(df_sentences)    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-28
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 2013-05-21
    相关资源
    最近更新 更多