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

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

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

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:

确定