0

您好,我编写了这个程序来重新格式化文件中的信息,以便它用逗号分隔,而不是它所具有的分隔符“|”,现在我这样做了,我想创建另一个函数,使用重新格式化的信息来编写某些使用索引将文件中的信息放入字典中,我的问题实际上是这样做的,因为我总是尝试使用 for 循环并且它不起作用。我在理解如何使用字典时遇到了一些麻烦,这似乎很简单,但我如何将信息输出访问到字典,它是否创建,或者我是否必须创建一个输出文件来存放该信息?

def dicList():
    dictList = csv.reader(open('C:/Python/data.txt', 'rb'))
    for row in dictList:
        newRow= ' '.join(row)
        listOne = newRow.replace('|',',')

另一件小事,这个函数输出像这样的值"hash,version,product,os

没有引号,所以它不会输出为我想要的列表,我也不知道如何实现这一点。

我总体上要做的是编写字典,以便我可以将另一个文件中的值与它匹配,而我使用这种方法的原因是因为文件很大,所以我不能只是将它们相互运行以进行匹配。我希望使用这个字典来运行我的另一个文件中的值以将匹配输出到另一个文件中。如果没有意义,我可以澄清一下。

让我再澄清一下我拥有的信息在文件中,信息作为“数据,数据,数据”输出到该文件中,现在我通过函数将信息放在列表中

def dicList():
dictList = csv.reader(open('C:/Python/hashsetsdotcom_data.txt', 'rb'), delimiter = '|')
for row in dictList:
        print row[0], row[2]

我在这里打印的两个值是我想在字典中作为键值的值,但我希望它遍历整个文件,大约有 800 万行,我希望能够使用这些数据来运行另一个文件,与这个文件相关,并从那里提取值以将其与字典值匹配,然后将这些匹配的值输出到另一个文件中。所以最后我会有

“键,值”----与另一个文件中的“匹配”。

我应该更清楚,但没有意识到我应该有多具体。

这是我的代码现在所在的位置,我在尝试将另一个文本文件中的数据值与字典中的值匹配时遇到问题,这可能正确吗?遍历我有这些值的文件并运行脚本以检查它们是否与字典值匹配,然后像我在上一个函数中尝试做的那样输出所有三个?

def dicList():
dictList = csv.reader(open('C:/data.txt', 'rb'), delimiter = '|')
for row in dictList:
        print row[0], row[2]

def dictAppend():
output = []
fhand = open('C:/Python/lex.txt', 'w')
for row in dicList():
    one_entity = {row[0]:row[2]}
    output.append(one_entity)

def findMatch():
fhand = open('C:/Python/search.sql', 'r')
fig = open('C:/Python/lex.txt', 'w')
for line in fhand:
    if line[1] == dictAppend()[0]:
        fig.write(dictAppend()[0], dictAppend[1], line[13])
4

2 回答 2

3

根据评论,我将包括两种解决方案,一种是响应评论,另一种是假设存在诸如 CSV 的 Excel 方言之类的标题。

您的解决方案有什么问题是您没有设置分隔符来反映数据

def dicList():
    dictList = csv.reader(open('C:/Python/data.txt', 'rb'), delimiter="|")
    for row in dictList:
       #the data should now be pre-separated into a list
       print row

这将通过管道而不是逗号分隔字段,不需要字典 - 它将像任何其他 csv 文件一样是一个列表。如果需要,您可以用逗号将它们连接起来并将它们写回输出。

要获得您似乎想要的字典格式,您需要按索引访问值并手动转换:

output = []
for row in dictList:
  one_entity = {row[0]:row[1],row[2]:row[3]}
  output.append(one_entity)

当然,假设数据像您在评论中所说的那样以交替的键值格式进行规范化。

key1|val1|key2|val2

带有标题的 csv 解决方案,每个字段都键入字典:

data_dictionary = dict()
line_no = 0

fields = 0
output = []

csv_data = csv.reader('C:\filepath')
for line in csv_data:
  if line_no == 0:
    #read the first line as the keys for the final dict
    fields = line
    line_no+=1
    continue

  field_index = 0
  one_entity = {}
  for answer in line:
    one_entity[fields[field_index]] = answer.strip()
  output.append(one_entity)
  line_no+=1

这些解决方案的组合应该可以让您到达您需要的地方。

编辑

在他指出之前我没有意识到这一点,但 JF Sebastian 提到csv.dictReader要完成我上面的示例,如果没有为参数传递值,默认情况下它将使用 csv 文件的第一行作为字段名称fieldnames

http://docs.python.org/library/csv.html#csv.DictReader

于 2012-06-28T16:11:09.333 回答
0

字典创建键值 u 对,所以

Diclist = {}

制作一个空字典

diclist["hello"] = 5

使用键“hello”和值 5 进行条目

diclist["hello"] = [5,6,7,8,9]

用列表覆盖该条目

print diclist["hello"]

将打印该列表

for x in diclist

x 将是 diclist 中的所有值。

于 2012-06-28T16:07:00.620 回答