使用Python清除文本和停止字删除后,将数据从Json导入Excel



我有Json文件,其中包含我使用Scrapy从网站上抓取的数据,我的下一步是清除特殊字符和停止字中的数据文本,并将它们保存在Excel文件中以备下一步使用。数据如下:

{"title": ["u2605u2605 The New J7 - Social Offer u2605u2605"], "seller": ["Galaxy"]}

我需要做的:

  1. 读取每个项目

  2. 删除特殊字符,我不知道如何阅读,因为它们是这样解码的:\u2605\u2605

  3. 删除停止字

  4. 将新数据保存在Excel文件中

我读过很多关于将Json导入Excel的线程,但都声明了一种在不修改数据的情况下在整个块中一次性导入Json的方法。

编辑:

这是我读取json文件、编辑值并将其保存到excel的最后一段代码,我希望它也能帮助其他人。

import json
import pandas as pd
from nltk.corpus import stopwords
import re
import codecs
data = ""
stopwords_list = stopwords.words('english')
with codecs.open("data.json", 'r', 'utf8') as data_file:    
data = json.load(data_file)
for item in data:
for key in item:
if key == "title":
temp = str(item[key]).lower()
temp = re.sub('[`~!@#$^&*()-_=+{};:'",<.>/?\|[]★]', '', temp)
temp = ' '.join([word for word in temp.split() if word not in stopwords_list])
item[key] = temp
with codecs.open('new_data.json', 'w', 'utf8') as new_data_file:
json.dump(data, new_data_file)
df = pd.read_json(codecs.open('new_data.json','r','utf-8'))
df.to_excel('out.xlsx')

panda是您的朋友。

import pandas as pd
df = pd.read_json('{"title": ["u2605u2605 The New J7 - Social Offer u2605u2605"], "seller": ["Galaxy"]}')
# Remove unneeded special characters by encoding to ascii and then recoding to utf-8
df.title = df.title.str.encode('ascii', 'ignore')
df.title = df.title.str.decode('utf-8')
# Removing stopwords - you need a list called stopwords defining your stopwords
df.title = df.title.apply(lambda x: ' '.join([word for word in x.split() if word not in (stopwords)]))
# write to excel
df.to_excel('out.xlsx')

要获得一个停止语列表,如果你还没有,你应该调查nltk。

最新更新