以可在Python中排序的格式存储输出

以可在Python中排序的格式存储输出,python,python-3.x,pandas,Python,Python 3.x,Pandas,我正在学习Python,并尝试将存储在文件中的列表(逗号分隔)转换为一个数据存储,该数据存储可以用Python排序,每四个字符串填充一行。例如,如果文件中包含以下内容: 'apples are great' ,'neg': 0.485, 'neu': 0.392, 'pos': 0.123, 'compound': -0.812, 'crayons are waxy' ,'neg': 0.302, 'neu': 0.698, 'pos': 0.0, 'compound': -0.3818, 'a

我正在学习Python,并尝试将存储在文件中的列表(逗号分隔)转换为一个数据存储,该数据存储可以用Python排序,每四个字符串填充一行。例如,如果文件中包含以下内容:

'apples are great'
,'neg': 0.485, 'neu': 0.392, 'pos': 0.123, 'compound': -0.812,
'crayons are waxy'
,'neg': 0.302, 'neu': 0.698, 'pos': 0.0, 'compound': -0.3818,
'a happy girl'

,'neg': 0.0, 'neu': 1.0, 'pos': 0.0, 'compound': 0.0,
'a phone is alive' 
,'neg': 0.0, 'neu': 0.737, 'pos': 0.263, 'compound': 0.3612,..........
我想要一个具有以下内容的数据帧:

Subject           Neg    Neu    Pos    Compound 
apples are great  0.485  0.392  0.123  -0.812 
crayons are waxy  0.302  0.698  0.0    -0.3818 
a happy girl      0.0    1.0    0.0    0.0 
a phone is alive  0.0    0.737  0.263  0.3612 
我的目标是按复合列进行排序,并在第一列中查找单词的频率。 我觉得这应该是相对容易的,但是我试着读入一个数据帧,但是它变成了一行,每个值在一列中,然后还试着把它变成一个包含句子的textblob,再次得到错误的结果

提前谢谢你的帮助

我试过的样品

test = open('Heros_toSort.txt')
test2=test.readlines()
df = pd.DataFrame(test2, columns = ['name'])
df.assign(name=df.name.str.split(','))

Python有一个内置的库
csv
,可用于轻松读取数据。这可能也可以用标准i/o工具来执行,但这就是我的解决方案

在csv中,每行的第一个条目是引号中的名称,第二个到第五个条目是值,所有这些值都以相同的顺序显示。这些值在名称和模式后面有一个数字
。我们可以去掉名称周围的引号,以及冒号后面的数字,然后使用它制作一个
pandas
dataframe

导入csv
作为pd进口熊猫
数据=[]
在文件中打开('data.csv','r'):
c_reader=csv.reader(在_文件中,分隔符=',')
对于c_读取器中的行:
这一行=[]
#从每一行中,首先获取名称,去掉前导和尾随的“单引号”。
此\u行.append(行[0].strip().lstrip('\'').rstrip('\'')
#获取剩余的值
对于范围(1,列(行))中的i:
#所有值都以相同的顺序出现在“:”模式之后。在“:”上拆分
#然后得到分割的后半部分——这是我们正在寻找的价值
此_row.append(row[i].split(“:”,1)[1])
#将其添加到数组中
data.append(此_行)
#从csv文件生成数据帧
df=pd.DataFrame(数据,列=['Name','neg','neu','pos','component'])
打印(df)

那么,受试者的姓名和值总是在不同的行上?此外,在您的输入数据示例中还有一个空行。这是一个复制粘贴错误,还是你真的有随机的空行?您从何处获取此数据?这将返回以下内容:回溯(最近一次调用):文件“/Users/ello.py”,第149行,在这一行中。append(行[i]。split(“:”,1)[1])indexer:列表索引超出范围听起来您的CSV格式不正确。你能发一个链接到它吗?
import re
import collections
import pandas as pd

# The input is a single text line
stringinput = ("'apples are great','neg': 0.485, 'neu': 0.392, 'pos': 0.123,"
              + " 'compound': -0.812,'crayons are waxy','neg': 0.302, "
              + "'neu': 0.698, 'pos': 0.0, 'compound': -0.3818,'a happy girl',"
              + "'neg': 0.0, 'neu': 1.0, 'pos': 0.0, 'compound': 0.0,"
              + "'a phone is alive' ,'neg': 0.0, 'neu': 0.737, 'pos': 0.263,"
              + " 'compound': 0.3612")

# clean up text file
remap = {
    ord('\'') : ''
}

cleaned_text = stringinput.translate(remap)
# remove tags of values
f_test = re.sub( "neg:|neu:|pos:|compound:*", '', cleaned_text )
# break text into list
string_to_list = f_test.split(',')
# create list of lists with
# list comprehension.
# Each inner list contains
# 5 elements, such as 
# 'Subject', 'Neg','Neu','Pos','Compound'
list_to_df = [ string_to_list[i : i + 5] 
              for i in range(0, len(string_to_list), 5) ]
# generate pandas dataframe
df = pd.DataFrame(
    list_to_df,
    columns = ['Subject', 'Neg','Neu','Pos','Compound']
    )
# sort dataframe based on Compound
df_sorted = df.sort_values(['Compound'],
                 ascending = False
                 )
# word frequency
freq = df_sorted['Subject'].to_list()

freq_dict = collections.defaultdict(int)

for text in freq:
  for word in text.split(' '):
    freq_dict[word] += 1

for word, freq in freq_dict.items():
  print(word, freq, sep = '\t')