【问题标题】:how should i use split in python for multiple delimiters? [duplicate]我应该如何在 python 中使用 split 来分隔多个分隔符? [复制]
【发布时间】:2021-12-29 13:27:07
【问题描述】:

如何将"five 6 seven, eight!nine" 之类的字符串拆分为只有单词?我的意思是删除所有内容并计算单词?或者换句话说,如何用几个分隔符分割一个句子?我不应该使用库。

def count_words(string):
    testlen=string.split( )
    
    return len(testlen)

【问题讨论】:

标签: python split


【解决方案1】:

我正在添加这个解决方案,即使发现了重复的答案,因为你说

  1. 不要使用任何库(我认为即使re 也是不允许的?)
  2. 你不知道可能会出现什么分隔符

例子:

 def count_words(string):
        def ch(char):
            return char if char.isalnum() else " "
        return [ch(c) for c in string].count(" ")

它只是将任何非字母数字替换为空格,然后计算空格。可能不是超级蟒蛇!

【讨论】:

  • 它不适用于 count_words("test3four") ,它返回 0,假设为 2。
  • 这个想法是只考虑字母和数字是有效的,所以这里只有 1。你应该根据你的需要即兴逻辑。
【解决方案2】:

我推荐使用 re.split()。 一次分割多个字符是一种高效且常用的方法。

import re

string = "This, is a sample string"

print("initial string is : " + string) 

splitted_string = re.split(', |_|-|!', data)

我希望它可以帮助。看看它的文档。 https://docs.python.org/3/library/re.html

【讨论】:

  • 我们不允许导入,
【解决方案3】:
def count_words(string):
    alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," "]
    for l in string:
        if l not in alphabet:
            string = string.replace(l, " ")#replacing non alphabit with space
            string = string.replace("  ", " ")#in case of 2 spaces resulted, replacing them with 1 space
    testlen = string.split(" ")
    print(testlen)
    return len(testlen)


string = "five 6 seven, eight!nine"
count_words(string)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2022-06-28
    • 2017-07-03
    • 2011-12-13
    • 2014-11-26
    • 1970-01-01
    相关资源
    最近更新 更多