将txt文件转换为字典以计算“.csv”文件。

huangapple go评论99阅读模式
英文:

converting txt file to dictionary to count ".csv"

问题

我必须计算每行中的 ".csv" 并将它们分配给相同的键值。

我有一个名为 "files.txt" 的文本文件,其中包含 7 行:

  1. test/file1.txt
  2. test/file2.txt.gz
  3. test/file3.csv
  4. test/file4.txt
  5. test2/file5.csv
  6. test2/file6.txt
  7. test2/file7.csv

这是我的代码:

  1. res = {}
  2. for line in open('files.txt').readlines():
  3. key, val = line.strip().split('/')
  4. x = 0
  5. if '.csv' in val:
  6. x += 1
  7. print(key, ":", x)

这将产生以下输出:

  1. test : 1
  2. test2 : 1
  3. test2 : 1

请注意,我是新手程序员。

英文:

`I have to count ".csv" in each line and assign them to the same key value.

I have text file "files.txt" with 7 line of

  1. test/file1.txt
  2. test/file2.txt.gz
  3. test/file3.csv
  4. test/file4.txt
  5. test2/file5.csv
  6. test2/file6.txt
  7. test2/file7.csv

Here's my code:

  1. res = {}
  2. for line in open('files.txt').readlines():
  3. key, val = line.strip().split('/')
  4. x =0
  5. if '.csv' in val:
  6. x+=1
  7. print(key, ":", x)

which yields the following output:

  1. test : 1
  2. test2 : 1
  3. test2: 1

notice that I am new to programing`

答案1

得分: 1

在这里,我保留了你的代码不变,但利用了res字典来统计每个键中.csv出现的总次数:

  1. res = {}
  2. for line in open('files.txt').readlines():
  3. key, val = line.strip().split('/')
  4. if '.csv' in val:
  5. res[key] = res.get(key, 0) + 1
  6. for key, val in res.items():
  7. print(f"{key}:{val}")
  8. # test:1
  9. # test2:2
英文:

Here, I've kept your code intact, but made used of the res dictionary to count the total number of occurrences of '.csv' for each key:

  1. res = {}
  2. for line in open('files.txt').readlines():
  3. key, val = line.strip().split('/')
  4. if '.csv' in val:
  5. res[key] = res.get(key, 0) + 1
  6. for key, val in res.items():
  7. print(f"{key}:{val}")
  8. # test:1
  9. # test2:2

huangapple
  • 本文由 发表于 2023年3月8日 15:31:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75670334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定