计算字符串中以逗号分隔的元素个数
Count the number of elements in a string separated by comma
我正在处理如下文本字符串:
LN1 2DW, DN21 5BJ, DN21 5BL, ...
在Python中,如何计算逗号之间的元素个数?每个元素可以由 6、7 或 8 个字符组成,在我的示例中显示了 3 个元素。分隔符始终为逗号。
我从来没有做过任何与文本挖掘相关的事情,所以这对我来说是一个开始。
如果逗号 (,
) 是分隔符,您可以简单地在结果上使用 str.split
on the string and then len(..)
:
text = 'LN1 2DW, DN21 5BJ, DN21 5B'
number = len(text.split(','))
您还可以重复使用元素列表。例如:
text = 'LN1 2DW, DN21 5BJ, DN21 5B'
tags = text.split(',')
number = len(tags)
#do something with the `tags`
你可以统计逗号的个数:
text.count(",") + 1
# 3
Willien 和 Psidom 已经提到 count
,
我只是想补充一点,在 python 中,字符串也是可迭代的,因此也可以应用列表理解:
n = len([c for c in ','+text if c==','])
或者
n = sum(1 for c in ','+text if c==',')
我正在处理如下文本字符串:
LN1 2DW, DN21 5BJ, DN21 5BL, ...
在Python中,如何计算逗号之间的元素个数?每个元素可以由 6、7 或 8 个字符组成,在我的示例中显示了 3 个元素。分隔符始终为逗号。
我从来没有做过任何与文本挖掘相关的事情,所以这对我来说是一个开始。
如果逗号 (,
) 是分隔符,您可以简单地在结果上使用 str.split
on the string and then len(..)
:
text = 'LN1 2DW, DN21 5BJ, DN21 5B'
number = len(text.split(','))
您还可以重复使用元素列表。例如:
text = 'LN1 2DW, DN21 5BJ, DN21 5B'
tags = text.split(',')
number = len(tags)
#do something with the `tags`
你可以统计逗号的个数:
text.count(",") + 1
# 3
Willien 和 Psidom 已经提到 count
,
我只是想补充一点,在 python 中,字符串也是可迭代的,因此也可以应用列表理解:
n = len([c for c in ','+text if c==','])
或者
n = sum(1 for c in ','+text if c==',')