本帖最后由 icestick8586 于 2018-8-17 17:01 编辑
1、一个txt文件中已知数据为:
C4D
C4D/maya
C4D
C4D/su
C4D/max/AE
统计每个字段出现的次数,比如C4D,maya,请用最熟悉的语言或者伪代码实现该需求
解决方案一、
- def count_test(file_path):
- list1 = []
- with open(file_path, 'r') as f:
- for line in f.readlines():
- result = line.strip().split('/')
- list1.extend(result)
- result = {}
- for i in list1:
- if i in result:
- result[i]=result[i] + 1
- else:
- result[i]=1
- return result
- r = count_test("d:\\test.txt")
- print(r)
复制代码
解决方案一优化
- def count_test(file_path):
- result = {}
- with open(file_path, 'r') as f:
- list1 = [line.strip().split('/') for line in f.readlines()]
- for i in list1:
- for j in i:
- result[j] = result[j] + 1 if j in result else 1
- return result
- r = count_test("d:\\test.txt")
- print(r)
复制代码
|
|