我已经阅读了有关如何在python中删除字符串的非ASCI字符的现有文章。但是我的问题是,当我要将其应用于从csv文件读取的数据框时,它不起作用。知道为什么吗?
import pandas as pd
import numpy as np
import re
import string
import unicodedata
def preprocess(x):
# Convert to unicode
text = unicode(x, "utf8")
# Convert back to ascii
x = unicodedata.normalize('NFKD',text).encode('ascii','ignore')
return x
preprocess("Ludwig Maximilian University of Munich / M\xc3\xbcnchen (LMU) and Siemens AG")
“慕尼黑路德维希马克西米利安大学(LMU)和西门子公司”
df = pd.DataFrame(["Ludwig Maximilian University of Munich / M\xc3\xbcnchen (LMU) and Siemens AG"])
df.columns=['text']
df['text'] = df['text'].apply(lambda x: preprocess(x) if(pd.notnull(x)) else x)
df['text'][0]
“慕尼黑路德维希马克西米利安大学(LMU)和西门子公司”
df1 = pd.read_csv('sample.csv')
df1['text'] = df1['text'].apply(lambda x: preprocess(x) if(pd.notnull(x)) else x)
df1['text'][0]
“慕尼黑路德维希马克西米利安大学/ M \ xc3 \ xbcnchen(LMU)和西门子公司”
答案 0 :(得分:2)
这是因为pandas正在读取文件中的文本作为原始字符串。它基本上等同于:
df = pd.DataFrame({"text": [r"Ludwig Maximilian University of Munich / M\xc3\xbcnchen (LMU) and Siemens AG"]})
要使标准化正常工作,您必须处理转义的字符串。只需修改您的preprocess
函数:
def preprocess(x):
decoded = x.decode('string_escape')
text = unicode(decoded, 'utf8')
return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')
应该使用后缀:
>>> df = pd.DataFrame({"text": [r"Ludwig Maximilian University of Munich / M\xc3\xbcnchen (LMU) and Siemens AG"]})
>>> df
text
0 Ludwig Maximilian University of Munich / M\xc3...
>>> df['text'] = df['text'].apply(lambda x: preprocess(x) if(pd.notnull(x)) else x)
>>> df
text
0 Ludwig Maximilian University of Munich / Munch...