英文:
converting txt file to dictionary to count ".csv"
问题
我必须计算每行中的 ".csv" 并将它们分配给相同的键值。
我有一个名为 "files.txt" 的文本文件,其中包含 7 行:
test/file1.txt
test/file2.txt.gz
test/file3.csv
test/file4.txt
test2/file5.csv
test2/file6.txt
test2/file7.csv
这是我的代码:
res = {}
for line in open('files.txt').readlines():
key, val = line.strip().split('/')
x = 0
if '.csv' in val:
x += 1
print(key, ":", x)
这将产生以下输出:
test : 1
test2 : 1
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
test/file1.txt
test/file2.txt.gz
test/file3.csv
test/file4.txt
test2/file5.csv
test2/file6.txt
test2/file7.csv
Here's my code:
res = {}
for line in open('files.txt').readlines():
key, val = line.strip().split('/')
x =0
if '.csv' in val:
x+=1
print(key, ":", x)
which yields the following output:
test : 1
test2 : 1
test2: 1
notice that I am new to programing`
答案1
得分: 1
在这里,我保留了你的代码不变,但利用了res
字典来统计每个键中.csv
出现的总次数:
res = {}
for line in open('files.txt').readlines():
key, val = line.strip().split('/')
if '.csv' in val:
res[key] = res.get(key, 0) + 1
for key, val in res.items():
print(f"{key}:{val}")
# test:1
# 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:
res = {}
for line in open('files.txt').readlines():
key, val = line.strip().split('/')
if '.csv' in val:
res[key] = res.get(key, 0) + 1
for key, val in res.items():
print(f"{key}:{val}")
# test:1
# test2:2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论