【问题标题】:How do I turn a column of lists into strings?如何将一列列表转换为字符串?
【发布时间】:2021-05-02 22:11:19
【问题描述】:
  Speaker ID                                         Utterances
0         S1  [alright Sue now it's like uh i dropped like C...
1         S2  [this year? this term?, ri- oh but you dropped...
2         S3  [yeah. hi, hi, yeah i already signed [S2: okay...
3         S4  [back in i was like w- what is that?, yeah and...
4         S5  [okay well i'm not here for a drop-add class [...
5         S6  [me, yeah. that's right, i have a question lik...
6         S7  [hello, hi, what was your name?, i thought i o...

实际上,最终目标是创建一个新列,其中“话语”列下的所有内容都已删除标点符号并已被标记化。我只需要先把字符串列表转成字符串,对吧?

附:我知道格式很奇怪,但我不知道如何解决这个问题,而且我还没有在任何地方找到答案。如果有人能告诉我我应该如何包含我正在使用的文本以便它看起来不奇怪,那就太好了。谢谢!

【问题讨论】:

  • df.to_dict() 在此处发布干净的示例数据。
  • df.Utterances.str.join(SEP),其中SEP 是单词之间所需的分隔符。

标签: python dataframe tokenize


【解决方案1】:

一个想法可能是:

import pandas as pd
from string import punctuation
import re
df = pd.DataFrame({'Utterances':[["me, yeah. that's right, i have a question lik"], ["hello, hi, what was your name?, i thought i o"]]})

df['Utterances'] = df['Utterances'].str.join(' ')
pattern = r'|'.join([re.escape(e) for e in punctuation])
df['Utterances'] = df['Utterances'].str.replace(pattern, '')

【讨论】:

  • 非常感谢!这行得通。能否解释一下join后括号内的部分?
  • 很高兴我能提供帮助,也请考虑接受我的回答。 punctuation 包含所有标点符号作为单个字符串。 [e for e in punctuation] 通过标点符号循环并创建一个列表,基本上是 for 循环的更紧凑版本(谷歌:列表理解)re.escape 是必需的,因为例如点字符“。”在正则表达式中作为通配符代表:每个可能的字符。但是我们想替换点本身并且不要将它用作通配符。希望这可以帮助。编码愉快。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
相关资源
最近更新 更多