【问题标题】:How to merge multiple similar words into one python如何将多个相似词合并到一个python中
【发布时间】:2021-08-03 11:22:11
【问题描述】:

我有一个单词列表

names = ['ASO', 'TSLA', 'GME']

我有一个数据框

                                dt  ...                                               text
0        2021-03-19 14:59:49+00:00  ...  I only need ASO:"@ASO[]ASO^%$ASO to hit 20 eod to make up for a...
1        2021-03-19 14:59:51+00:00  ...                                 Oh this isn’t good
2        2021-03-19 14:59:51+00:00  ...  lads why is my account covered in more red ink..

如果列表中的单词与每一行匹配,我需要创建一个函数。 如果列表中有 3 个或更多类似的单词,如第一行,我只想保留这个单词的一个版本,记住标志。我不在乎是否会有迹象,但保留一个版本的单词很重要 我想要的输出

                                dt  ...                                               text
0        2021-03-19 14:59:49+00:00  ...  I only need ASO to hit 20 eod to make up for a...
1        2021-03-19 14:59:51+00:00  ...                                 Oh this isn’t good
2        2021-03-19 14:59:51+00:00  ...  lads why is my account covered in more

这是我尝试过的

price = pd.read_csv('top_20_tickers.csv')
names = list(price.columns)
names.pop(0)
discussion = pd.read_csv('wsb_comments.csv', error_bad_lines=False, index_col=False, dtype='unicode')
discussion = discussion.drop_duplicates('text')
discussion = discussion[discussion['text'].notnull()]


def check_words(sentence, names):
    words = sentence.split()
    count = 0
    for word in words:
        if word in names:
            count += 1
    return count > 3


discussion['Contains_4+_words'] = discussion.apply(lambda r: check_words(r.text, names), axis=1)
discussion = discussion[discussion['Contains_4+_words'] == False]

但它会删除整行但我需要合并某些单词 谢谢

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 您的文字令人困惑。要么在其中放置适当的标点符号,要么尝试将其作为项目列表。
  • 请看评论
  • 为什么会有两个数据框?第二个是关于什么的?
  • 第二个是我想查看第 1 行的输出,然后是第 1 行的固定版本

标签: python pandas dataframe


【解决方案1】:

这行得通吗?


words = ['ASO', 'TSLA']
def merge_words(words, phrase):
    for word in words:
        sections = phrase.split(word)
        if len(sections)>= 3:
            res = sections[0]  + word + sections[-1]
            print(res)
            return res
        else:
            return phrase
f = lambda x: (merge_words(words, x['text']))

discussion['text'] = discussion.apply(f, axis=1)

PS:如果您直接在代码中提供 Dataframe 示例,则更容易迭代并给出答案

【讨论】:

  • 它告诉我 AttributeError: 'list' object has no attribute 'split' on line section = phrase.split(word)
  • 在“文本”列中,您有时有列表,而不是字符串?
  • 本栏目只有文字
  • names 是列表,其他都是字符串
  • 是的,我刚刚复制了你的代码,这就是我得到的错误
猜你喜欢
  • 1970-01-01
  • 2017-05-04
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-14
  • 1970-01-01
  • 2016-05-25
相关资源
最近更新 更多