簡體   English   中英

如何提取csv文件的內容並將它們放在dict文件類型中而不使用csv模塊。 [蟒蛇]

[英]How to extract contents of a csv file and place them in a dict file type without using csv module. [python]

以下是文件中的信息:

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

我正在試圖弄清楚如何打開一個文件,然后使用Part no將它的內容存儲到字典中。 作為關鍵和其他信息作為價值。 所以我希望它看起來像這樣:

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

我能夠將文件中的文本存儲到列表中,但我不確定如何為一個鍵分配多個值。 我試圖這樣做而不導入任何模塊。 我一直在使用基本的str方法,列表方法和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.

也許是這樣的:

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:])

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語句)。

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

而不是閱讀整個文件,然后不得不拆開它,通常更容易逐行處理文件。 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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM