python过滤字符串仅显示少于两个词的标签

4 投票
3 回答
1364 浏览
提问于 2025-04-16 10:32

我想从一串标签中提取出前10个只包含少于两个单词的标签。现在不太确定我的代码是不是朝着正确的方向在走……

mystring = 'one, two, three, three three three, four four four, five, six'

for text in mystring:
    number = len(mystring.split())
        if text >= 2:

print number

我基本上想要输出的结果是:一个、两个、三个、五、六

3 个回答

1

有点不同……

mystring = 'one, two, three, three three, four, five, six'

for text in mystring.split(","):
    number = len(text.strip().split()) #split by default does it by space, and strip removes spaces at both ends of the string
    if number < 2:
        #this string contains less than two words
        print text

首先用逗号 , 把内容分开,然后对每一部分再用空格进行一次分割。

3
>>> mystring = 'one, two, three, three three three, four four four, five, six'
# first separate the string into into a list and strip the extraneous spaces off..
>>> str_list = map(lambda s: s.strip(), mystring.split(','))
# then create a new list where the number of "numbers" in each list item are less or equal than two
>>> my_nums = filter(lambda s: len(s.split()) <= 2, str_list))
>>> print my_nums
['one', 'two', 'three', 'five', 'six']

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。

1
[item.strip() for item in mystring.split(',') if len(item.split()) < 2]

“这是从每个用逗号分开的字符串两端去掉空格的结果。如果用空格分开的话,得到的子项会少于两个。”

撰写回答