1

以下是文件中的信息:

"Part no.","Description","Price"
"453","Sperving_Bearing","9900"
"1342","Panametric_Fan","23400"
"9480","Converter_Exchange","93859"

我试图弄清楚如何打开文件,然后使用零件号将其内容存储到字典中。作为键,其他信息作为值。所以我希望它看起来像这样:

{Part no.: "Description,Price", 453: "Sperving_Bearing,9900", 1342: "Panametric_Fan,23400",9480: "Converter_Exchange,93859"}

我能够将文件中的文本存储到一个列表中,但我不确定如何为一个键分配多个值。我试图在不导入任何模块的情况下做到这一点。我一直在使用基本的 str 方法、list 方法和 dict 方法。到目前为止,这是我的代码:(我假设将正确输入文件名)

textname = input("ENter a file")
thetextfile = open(textname,'r')
print("The file has been successfully opened!")
thetextfile = thetextfile.read()
file_s = thetextfile.split()
holder = []
ck = 0
for c in range(len(file_s)):
   holder.append(file_s[c])
   ck = ck+1
   if(ck == 3):
       holder.insert(c,'\n')
       count = 0
holder_string = "".join(holder)
holder = holder_string.split("\n")
wordlist = {}

#kind of stuck here.
4

4 回答 4

1

或许是这样的:

wordlist = {}
with open(textname, 'r') as thetextfile:
  for line in thetextfile:
    line = line.split()
    wordlist[line[0]] = line[1:]

这使得 dict 值成为(更方便的)剩余项目的列表。但是,如果您真的想要上面的“,”字符串语法,也许:

wordlist = {}
with open(textname, 'r') as thetextfile:
  for line in thetextfile:
    line = line.split()
    wordlist[line[0]] = ",".join(line[1:])
于 2013-07-24T02:36:58.987 回答
1

SCV 是一个逗号分隔的变量文件,所以我假设每个变量确实用逗号分隔:

f = open("myfile.csv", 'r')
data = f.read().split('\n') #separates the contents into lines with while leaving out the newline characters
myDict = {}
for x in range(len(data)):
    data[x] = data[x].split(',') #makes each line a list of variables. If the data is contain extra white spaces use the strip() method
    myDict[data[x][0]] = (data[x][1], data[x][2]) #this will make the dictionary like you described in the question

不要忘记丢失您的文件(除非您使用该with语句)。

于 2013-07-24T02:40:57.833 回答
1
import re
data = {}
with open('input') as f:
    # read headers to make keys for hashes
    headers = re.split(r'\t|\s\s+', f.readline().rstrip())
    # skip the dashes
    f.readline()
    # read the actual data
    for line in f:
         linedata = line.split()
         data[linedata[0]] = { k : v for k, v in zip(headers, linedata) }
# print the parsed data
for part, info in data.items():
    print part
    for k, v in info.items():
        print "\t{} => {}".format(k, v)

输出

1342
    Part no. => 1342
    Description => Panametric_Fan
    Price => 23400
453
    Part no. => 453
    Description => Sperving_Bearing
    Price => 9900
9480
    Part no. => 9480
    Description => Converter_Exchange
    Price => 93859
于 2013-07-24T04:46:59.060 回答
0

与其读取整个文件,然后将其拆分,不如逐行处理文件通常更容易。Python 使这变得非常容易。

parts = {}

with open(file_name) as fh:
    # Ignore the first two lines. They aren't data.
    next(fh)
    next(fh)

    # Opened files are iterable, line by line.
    for line in fh:
        # Store the separate data elements separately, not munged together.
        i, d, p = line.split()
        parts[i] = {'id': i, 'desc': d, 'price': p}
于 2013-07-24T02:44:25.723 回答