【问题标题】:Update list of tuples in python更新python中的元组列表
【发布时间】:2021-11-17 13:05:54
【问题描述】:

我有一个数据框,其中每一行都是一个元组列表,例如

[('This', 'DET'), ('is', 'VERB'), ('an', 'DET'), ('example', 'NOUN'), ('text', 'NOUN'), ('that', 'DET'), ('I', 'PRON'), ('use', 'VERB'), ('in', 'ADP'), ('order', 'NOUN'), ('to', 'PART'), ('get', 'VERB'), ('an', 'DET'), ('answer', 'NOUN')]

然后,在每一行中,我用<IN>word</IN><TA>word</TA> 标记一些元组的单词。例如:

updated_word : <IN>example</IN>
updated_word  : <TA>answer</TA>

我想更新数据框的每一行,使其包含我的元组的更新版本,并且有类似的内容:

[('This', 'DET'), ('is', 'VERB'), ('an', 'DET'), ('<IN>example</IN>', 'NOUN'), ('text', 'NOUN'), ('that', 'DET'), ('I', 'PRON'), ('use', 'VERB'), ('in', 'ADP'), ('order', 'NOUN'), ('to', 'PART'), ('get', 'VERB'), ('an', 'DET'), ('<TA>answer</TA>', 'NOUN')]

我已设法分别更新每个元组,但我找不到将它们附加到数据框行并更新每行的 元组列表 的方法。有人可以帮我吗?

代码如下:

cols = list(df.columns)[4:]
for idx, row in df.iterrows():
    doc = nlp(row['title'])
    pos_tags = [(token.text, token.pos_) for token in doc if not token.pos_ == "PUNCT"]

    for position, tuple_ in enumerate(pos_tags, start=1):
        word = tuple_[0]
        spacy_pos_tag = tuple_[1]
        word = re.sub(r'[^\w\s]', '', word)
        for col in cols:
           if position in row[col]:
              word = f'<{col.upper()}>{word}</{col.upper()}>'
           else:
              word = word
         new_text.append(' '.join(word))
         tuple_ = (word, spacy_pos_tag)
        pos_tags[position] = tuple_
df['title'] = pos_tags
print(df.title)

更新

我使用@Peter White 的建议来获取元组列表,但是当我想将每个 pos_tags 元组列表附加到名为df['title'] 的数据框列的每一行中时,我仍然遇到错误。错误信息是:

    raise ValueError(
 ValueError: Length of values (23) does not match length of index (500)

【问题讨论】:

  • 你试过 pos_tags[position] = tuple_ 吗?最后打印在哪里?
  • pos_tags[position] = tuple_ IndexError: list assignment index out of range
  • 从枚举中删除 start=1。它从 1 开始计数,而不是 0,所以最后,它试图访问大于列表大小的元素 1

标签: python nlp tuples


【解决方案1】:

把 pos_tags[position] = tuple_?最后,并从枚举中删除 start=1:

cols = list(df.columns)[4:]
for idx, row in df.iterrows():
    doc = nlp(row['title'])
    pos_tags = [(token.text, token.pos_) for token in doc if not token.pos_ == "PUNCT"]

    for position, tuple_ in enumerate(pos_tags):
        word = tuple_[0]
        spacy_pos_tag = tuple_[1]
        word = re.sub(r'[^\w\s]', '', word)
        for col in cols:
           if position in row[col]:
              word = f'<{col.upper()}>{word}</{col.upper()}>'
           else:
              word = word
         new_text.append(' '.join(word))
         tuple_ = (word, spacy_pos_tag)
         print(tuple_)
         pos_tags[position] = tuple_

【讨论】:

  • 嗨,你能看看我更新的问题吗?我使用了您的建议,但是当我尝试将每个元组列表放入数据框列的每一行时,我收到此值错误
  • 我认为你有很多 token.pos_ == "PUNCT",你已经过滤掉了,所以现在它们的长度不相等。您可以尝试将该部分移动到 for 循环中,这样您就不会修改这些行但仍将它们保留在最终结果中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-07
  • 2019-05-15
  • 1970-01-01
  • 1970-01-01
  • 2016-12-28
  • 1970-01-01
  • 2021-10-30
相关资源
最近更新 更多