Skip to main content
 首页 » 编程设计

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

2024年11月01日8lautakyan007

我正在努力学习 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  

我的目标是按复合列排序,并查找第一列中的单词频率。 我觉得这应该相对容易,但曾尝试读入一个数据框,但它变成了一行,每个值都在一列中,然后还试图将它变成一个带有句子的文本 block ,但再次得到不正确的结果。

提前感谢您的帮助。

我尝试过的例子

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 数据框。

import csv 
import pandas as pd 
 
data = [] 
 
with open('data.csv', 'r') as in_file: 
  c_reader = csv.reader(in_file, delimiter=',') 
  for row in c_reader: 
    this_row = [] 
 
    #from each row, get the name first, stripping the leading and trailing ' single quotes. 
    this_row.append(row[0].strip().lstrip('\'').rstrip('\'')) 
 
    #get the remaining values 
    for i in range(1, len(row)): 
 
      #all values appear after a ': ' pattern, in the same order. split on ': ' 
      #and get the second half of the split - it's the value we're looking for 
      this_row.append(row[i].split(": ",1)[1]) 
 
    #add this to the array 
    data.append(this_row) 
 
#make a dataframe out of the csv file 
df = pd.DataFrame(data, columns=['Name', 'neg', 'neu', 'pos', 'compound']) 
print(df) 

Demo