如何在不使用拆分方法的情况下从字符串中挑选单词?

2024-09-27 00:19:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,看起来像“ABC DEF GHI”,我希望能够创建一个只有“ABC”或“DEF”或“GHI”的新字符串。我试图使用.isalpha方法来确定字符串何时从字母变成空格。这就是我的代码的样子:

def get_word(chars: str, width: int) -> str:    
    word = ""
    for i in range(len(chars)):
        if chars[i].isaplpha():
            word += chars[i]
            if chars[i].isspace():
                break
    return word

但是,我得到一个未解决的属性引用错误,因为我的输入需要是字符串。这是什么意思?它不允许我使用。isalpha。但是如果i=1,那么chars[i]=“B”是字母顺序,所以我很困惑

我不允许使用拆分方法。。。请帮忙


Tags: 方法字符串代码ifdef字母word空格
3条回答

您可以在递归中使用^{}^{},如以下示例所示:

使用str.partition():

def split1(string, delim=' '):
    first, sep, rest = string.partition(delim)
    return (
        [first] if first else []
    ) + split(rest, delim) if sep else ([first] if first else [])

使用str.find():

def split2(string, sep=' '): 
     if not sep: 
         raise ValueError('separator length must be >= 1') 
     index = string.find(sep) 
     if index < 0: 
         return [string] if string else [] 
     if len(sep) > 1: 
         index =  len(sep) if not index else index 
         first, rest = string[:index], string[index:] 
     else: 
         first, rest = string[:index], string[index + 1:] 
     return ([first] if first != sep else []) + split2(rest, sep)

测试:

word = 'ABC DEF GHI'
seps = [' ', 'DEF', 'ABC', 'GHI', 'C ']
for sep in seps:
    print(split1(word, sep), split2(word, sep))

输出:

['ABC', 'DEF', 'GHI'] ['ABC', 'DEF', 'GHI']
['ABC ', ' GHI'] ['ABC ', ' GHI']
[' DEF GHI'] [' DEF GHI']
['ABC DEF ', ''] ['ABC DEF ']
['AB', 'DEF GHI'] ['AB', 'DEF GHI']

性能比较:

%timeit split1(word)
690 ns ± 4.56 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit split2(word)
1.18 µs ± 34.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

如果您正在寻找此问题的通用解决方案,可以使用正则表达式:

import re

a = "ABC DEF GHI"

output = re.findall('[A-Z]{3}', a)

print(f"""
        First item: {output[0]}
        Second item: {output[1]}
        Third item: {output[2]}
       """)

这将检索3个连续大写字母字符(A到Z)的所有实例

如果输入字符串还可以包括数字,如“AB3 DEF 2HI”,那么您也可以使用output = re.findall('\w{3}', a)

如果输入字符串具有不同长度的“字”,则可以使用output = re.findall('\w+', a),它将匹配任意数量的连续字符

要了解有关regex的更多信息,并亲自使用它,可以使用regexr.com

对于这类问题,您可能需要一个正则表达式

import re
input =  "ABC DEF GHI"

re.split(r'\s+')  # split on whitespace
>>> ['ABC', 'DEF', 'GHI']

re.match(r'\w+', input)  # get first word
>>> <re.Match object; span=(0, 3), match='ABC'>

re.findall(r'\w+', input)  # find all groups of 1+ alphanumeric "word" chars
>>> ['ABC', 'DEF', 'GHI']

re.sub(r'\b\s+\b', '-', input)      # replace all spaces between words with '-'
>>> 'ABC-DEF-GHI'

相关问题 更多 >

    热门问题