让我说我有以下文本文件。假设每个颜色名称都是一个帐户名称,我想知道它下面有多少人。所有帐户名都以“ /”或“-”开头。我共享的文件中有3个帐户。这是第一个单词出现在“颜色:”之后。因此,这里有3个帐户。红色,蓝色和黑色。因此,红色/测试/基础,红色img测试,红色零测试和红色复制测试都是帐户“红色”的一部分。然后我必须最后说出红色下有多少人。所以这里是红色的:4.
import re
for line in f.readlines():#gives array of lines
acc_name = re.split('; |, |\/|\-|\:', line)[1].strip()
我有数千行,因此,正如您所看到的,我不能真正指定“ red”或“ blue”之类的单词...它必须以某种方式阅读它们中的每一个,并查看它们是否与下一行。
现在,我正在执行以下操作以获取帐户名称。
@Multipart
@POST("test/test.post.json")
Call<APIResponseSiteDetails> addImages(@PartMap Map<String, RequestBody> params);
答案 0 :(得分:4)
我有一个使用Counter的解决方案:
import collections
data = """
---------------------------------
Color: red/test/base
person: latest
---------------------------------
Color: red-img-tests
person: latest
---------------------------------
Color: red-zero-tests
person: latest
---------------------------------
Color: red-replication-tests
person: latest
---------------------------------
Color: blue
person: latest
---------------------------------
Color: black/red-config-img
person: 7e778bb
person: 82307b2
person: 8731770
person: 7777aae
person: 081178e
person: c01ba8a
person: 881b1ad
person: d2fb1d7
---------------------------------
Color: black/pasta
person: latest
---------------------------------
Color: black/base-img
person: 0271332
person: 70da077
person: 3700c07
person: c2f70ff
person: 0210138
person: 083af8d
"""
print (data)
colors = ["black", "red", "blue"]
final_count = []
for line in data.split("\n"):
for color in colors:
if color in line:
final_count.append(color)
#break # Uncomment this break if you don't want to count
# two colors in the same line
final_count = collections.Counter(final_count)
print(final_count)
输出
Counter({'blue': 1, 'black': 3, 'red': 5})
Here是Python官方文档的链接和快速参考:
此模块实现专门的容器数据类型,以提供 Python通用内置容器的替代品dict, 列出,设置和元组。
答案 1 :(得分:0)
您可以使用内置软件包Collections中的Counter()
在此处阅读有关Counter() in Python 3.x的信息
from collections import Counter
data = "apple apple apple apple red red green green green green green black"
d = Counter(data.split())
print(d)
字典的特殊之处在于它不存储重复值,因此您可以使用这种介质来获取计数。
答案 2 :(得分:-1)
count = {}
example = "apple apple apple apple red red green green green green green black"
for i in example.split():
if i not in count:
count[i] = 1
elif i in count:
count[i] += 1
print(count)