2017-04-23 40 views
1

感谢您的阅读!我对此很陌生,但昨天我开始从网站提取数据(一个项目的名称及其相应的价格),并跳出如何使用Python 2.7为格式创建csv文件,格式为:price,item-name。现在我有一些数据要与它们进行比较,并获得给定项目名称的平均价格。我现在遇到的问题是每个网站上的项目名称(可能)略有不同。例如我的第一数据集给出了csv文件CSV文本清理和Python比较

4.0, Jungle Book 
5.0, "Peter Pan" 
4.0, Lady and the Tramp 

第二给出

5.0, Disney's Jungle Book 
6.0, Disney's Up 
4.0, Disney's Peter Pan 

第三给出

5.0, Up (DVD) 
4.0, Peter pan (DVD) 
6.0, "Lady and the Tramp" (DVD) 

最后,我想像

平均输出文件
4.5, Jungle Book 
5.0, Lady and the Tramp 
4.33, Peter Pan 
5.5, Up 

我的第一个问题是删除我的csv文件中的特殊字符,如“或某些词(如”迪士尼“,”(DVD)“)。我找到有关从csv文件中删除行和列的信息,但是我很难在这些元素内进行编辑。像这样的东西删除“(DVD)”之类的作品,但让我的CSV文件,甚至更大的混乱与更多的“和[人物..

import csv 
import string 

input_file = open('DesktopData.csv', 'r') 
output_file = open('fixformat.csv', 'w') 
data = csv.reader(input_file) 
writer = csv.writer(output_file,quoting=csv.QUOTE_ALL)# dialect='excel') 
specials = '(DVD)' 

for line in data: 
    line = str(line) 
    new_line = str.replace(line,specials,'') 
    writer.writerow(new_line.split(',')) 

input_file.close() 
output_file.close() 

一旦将工作了,我想借此均价对于给定的称号。我心目中的东西,但缺乏Python语法真正弄明白

Read all titles and put in mainlist; 
if title already exsists, ignore/dont make new row with title 
Read all files and compare with mainlist; 
if title is found, put corresponding price in new column behind title 

在我的头上这已经到输出中

Jungle Book, 4.0, 5.0 
Lady and the Tramp, 4.0, 6.0 
Peter Pan, 5.0, 4.0, 4.0 
Up, 6.0, 5.0 

一旦我得到这个我敢肯定我可以做到到一般的csv文件。任何建议非常感谢!

+0

你可能想看看导入熊猫,并与它玩。从查看pd.read_csv()方法开始。 – Aklys

回答

0

到目前为止,最难的部分就是找到相同的名称,区别很小的区别。在这里的解决方案中,我已经做出了一个简单的normalize_title函数,但它并不完美。我想它需要手动调整和扩展每个新的数据集。但是,从APPART,这里是你的问题,从多个CSV文件,连同电影标题在新的CSV文件中收集数据,然后存储的平均成本的解决方案:

import csv 

filenames = ['first.csv', 'second.csv', 'third.csv'] 
outfile = 'avg.csv' 

removables = ['[', ']', '"', "'", "Disney's", '(DVD)'] 
def nomalize_title(title): 
    for remove in removables: 
     title = title.replace(remove, '') 
    title = title.lower() # Correct capitalization is HARD 
    return title 

moviecosts = dict() 
for filename in filenames: 
    with open(filename, 'rb') as f: 
     reader = csv.reader(f) 
     for row in reader: 
      raw_title = row[1] 
      title = normalize_title(raw_title) 
      price = float(row[0]) 

      if not moviecosts.has_key(title): 
       moviecosts[title] = [] 

      moviecosts[title].append(price) 

with open(outfile, 'wb') as f: 
    writer = csv.writer(f) 
    for movie in moviecosts: 
     avg_cost = sum(moviecosts[movie])/len(moviecosts[movie]) 
     row = [avg_cost, movie] 
     writer.writerow(row) 

可以看出,我将不同的成本存储到列表字典中。对我而言,这似乎是手头问题最自然的数据结构。

+0

感谢您的时间,我刚刚运行它,目前它给了我1个单元格中的1个值的输出,这是数据库中所有dvd的总体平均值,但这绝对有帮助。标准化后我无法找到标题列表;在哪里可以找到'电影'中的标题? – Alex

+0

如果您只获得一个平均值,那意味着所有标题都被“归一化”为相同的字符串。如果您打印moviecosts字典 – JohanL

+0

如果我打印moviecosts,它会显示{None:[4.0,12.0,...,22.0]}所以没有标题保存?在变量资源管理器中,我可以看到raw_title上升到最后一个数据库的最后一个标题。而所有的数据库价格都在moviecosts – Alex