【问题标题】:Cleaning a dataset and removing special characters in python清理数据集并删除python中的特殊字符
【发布时间】:2020-09-15 14:38:24
【问题描述】:

我对这一切还很陌生,所以提前道歉。

我有一个数据集 (csv)。一列包含带有整个句子的字符串。这些句子包含错误解释的 utf-8 字符,如 ’ 和表情符号,如 🥳

所以数据框 (df) 看起来像这样:

           date                                                         text
0   Jul 31 2020       it’s crazy. i hope post-covid we can get it done🥳
1   Jul 31 2020       just sayin’ ...
2   Jul 31 2020       nba to hold first games in 'bubble' amid pandemic

目标是对文本进行情感分析。

  1. 是否最好删除所有特殊字符(如 , . ( ) [ ] + | -)来进行情绪分析?
  2. 如何做到这一点以及如何删除错误解释的 utf-8 字符,例如 ’

我自己尝试过使用我找到的一些代码并将其更改为我的问题。 这导致这段代码似乎什么也没做。 ’ 等字符仍在文本中。

spec_chars = ["…","🥳"]
for char in spec_chars:
    df['text'] = df['text'].str.replace(char, ' ')

我有点迷路了。 感谢您的帮助!

【问题讨论】:

  • 我只是在使用 df = pd.read_csv('xxx.csv') 也尝试了 df = pd.read_csv('xxx.csv', encoding = 'utf8') 没有' t改变任何东西
  • 你能不能试着把它改成read_csv('xxx.csv', encoding='windows-1252')——看起来不是UTF8。
  • @jsmart 然后我得到这个 UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 8303: character maps to
  • 此链接可能会有所帮助:stackoverflow.com/questions/45749093/… -- 解析字符编码可能涉及大量试验和错误,抱歉没有更好的答案
  • chardet 可能有帮助:pypi.org/project/chardet(在之前评论的 SO 文章中提到过)

标签: python pandas data-cleaning


【解决方案1】:

您可以像这样更改字符编码。 x是原帖中的一句话。

x = 'it’s crazy. i hope post-covid we can get it done🥳'
x.encode('windows-1252').decode('utf8')

结果是'it’s crazy. i hope post-covid we can get it done?'

【讨论】:

  • 看起来很有希望。如何将此应用于整个列而不是仅一个字符串?
【解决方案2】:

正如 jsmart 所说,使用 .encode .decode。由于该列是一个系列,您将使用 .str 将系列的值作为字符串访问并应用方法。

至于文字情绪,看NLTK。并看看它的例子sentiment analysis

import pandas as pd


df = pd.DataFrame([['Jul 31 2020','it’s crazy. i hope post-covid we can get it done🥳'],
                   ['Jul 31 2020','just sayin’ ...'],
                   ['Jul 31 2020',"nba to hold first games in 'bubble' amid pandemic"]],
                    columns = ['date','text'])

df['text'] = df['text'].str.encode('windows-1252').str.decode('utf8')

【讨论】:

    【解决方案3】:

    试试这个:

    df['clean_text'] = df['text'].apply(lambda x: ' '.join([word for word in x.split() if word.isalnum()])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 2014-05-15
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      相关资源
      最近更新 更多