Python:从文本文件获取数据并将其放入CSV文件;列表索引超出范围 [英] Python: Get data from a text file and put it in an CSV file ; List index out of range

查看:190
本文介绍了Python:从文本文件获取数据并将其放入CSV文件;列表索引超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对此的后续问题:

This is a follow up question to this: Python: Find keywords in a text file from another text file

我想将line.strip中的文本数据放入2列的CSV(或excel)文件中.

I want to put the textual data from line.strip to a CSV (or excel) file in 2 columns.

这是我的尝试:

import numpy as np
import pandas as pd
import csv

with open('C:\invoice.txt') as f:
    invoice_data = [line.strip() for line in f if line.strip()]

with open('C:\dict.txt') as f:
    dict_data = set([line.strip() for line in f if line.strip()])

for i in range(0, len(invoice_data), 2):
    if invoice_data[i] in dict_data:
        print(invoice_data[i: i + 2])

with open('C:\\Users\\fam_robo1\\Documents\\sample.csv','w') as csvfile:
    fieldnames = ['keyword','data']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for i in range(0, len(invoice_data), 2):
        writer.writerow ({'keyword':[invoice_data[i]] , 'data':[invoice_data[i+2]] })
    csvfile.close()

任何帮助将不胜感激.

完整追溯:

Traceback (most recent call last):   
 File "C:\Users\fam_robo1\Documents\keyword.py", line 20, in <module> writer.writerow ({'keyword':[invoice_data[i]] , 'data':[invoice_data[i+2]] }) 
 IndexError: list index out of range

推荐答案

提示在列表索引超出范围"消息中.编写行时,您同时引用invoice_data[i]invoice_data[i+2](尽管我不确定为什么将它们放在列表中,因为尝试将列表写为CSV元素也可能会造成麻烦).

The clue is in the "list index out of range" message. When writing rows you reference both invoice_data[i] and invoice_data[i+2] (though I am not sure why you put them in lists, since trying to write out a list as a CSV element will probably cause trouble too).

您的for语句可以直接将i保留为len(invoice_data)-1,并且显然在该值下,索引i+2超出了允许的索引范围-这样您就可以进行追溯.

Your for statement can take i right up to len(invoice_data)-1, and clearly at that value the index i+2 is outside the permissible index range - so you get the traceback.

您在评论中问为什么人们总是不赞成您的问题.我怀疑这是因为他们几乎没有花力气去理解错误的根源.在您提到的上一个问题中,您说我一直在获取索引错误.是否需要先将其存储在表中?"但您没有解释为什么会这样,或者甚至是它应该意味着什么.

You ask in a comment why people keep downvoting your questions. I suspect this is because they show little real effort to understand what the error actually is. In the previous question to which you refer you say "I keep on getting the Index Error. Do I need to store it in a table first?" but you don't explain why you think this would help, or indeed even what it is supposed to mean.

我怀疑您可能会在走路之前先尝试跑步,而尝试困难的问题会显示出一种精神,但在尝试寻求SO的帮助之前,您最好认真看一下所获得的输出-Python产生的消息大多数都具有含义,如果您不理解它们,那么也许应该首先尝试确定它们的含义.如果您确实无法理解此错误消息是什么意思",通常是可以接受的问题.

I suspect you may be trying to run before you can walk, and while attempting difficult problems shows some spirit, you would do well to look hard at the output you get before trying to recruit the assistance of SO - the messages Python produces mostly have meaning, and if you don't understand them then perhaps you should start by trying to determine what they mean. "What does this error message mean" is usually an acceptable question if you genuinely can't understand it.

随着学习的进行,毫无疑问,您将能够更好地确定程序出了什么问题,但是依靠其他人不会像您自己的理解力那样快速地理解.

As you learn you will doubtless become better able to determine what is going wrong with your programs, but relying on other people will not grow your understanding as quickly as your own efforts to comprehend.

这篇关于Python:从文本文件获取数据并将其放入CSV文件;列表索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆