试图计算字符串中的单词

Har*_*rry 9 python string loops function list

我正在尝试分析字符串的内容.如果它在单词中混合了标点符号,我想用空格替换它们.

例如,如果Johnny.Appleseed!是:输入a*good&farmer作为输入,则应该说有6个单词,但我的代码只将其视为0个单词.我不知道如何删除不正确的字符.

仅供参考:我正在使用python 3,我也无法导入任何库

string = input("type something")
stringss = string.split()

    for c in range(len(stringss)):
        for d in stringss[c]:
            if(stringss[c][d].isalnum != True):
                #something that removes stringss[c][d]
                total+=1
print("words: "+ str(total))
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 15

简单循环解决方案:

strs = "Johnny.Appleseed!is:a*good&farmer"
lis = []
for c in strs:
    if c.isalnum() or c.isspace():
        lis.append(c)
    else:
        lis.append(' ')

new_strs = "".join(lis)
print new_strs           #print 'Johnny Appleseed is a good farmer'
new_strs.split()         #prints ['Johnny', 'Appleseed', 'is', 'a', 'good', 'farmer']
Run Code Online (Sandbox Code Playgroud)

更好的方案:

使用regex:

>>> import re
>>> from string import punctuation
>>> strs = "Johnny.Appleseed!is:a*good&farmer"
>>> r = re.compile(r'[{}]'.format(punctuation))
>>> new_strs = r.sub(' ',strs)
>>> len(new_strs.split())
6
#using `re.split`:
>>> strs = "Johnny.Appleseed!is:a*good&farmer"
>>> re.split(r'[^0-9A-Za-z]+',strs)
['Johnny', 'Appleseed', 'is', 'a', 'good', 'farmer']
Run Code Online (Sandbox Code Playgroud)

  • `>>> len(re.findall(r'\ b\w +\b','Johnny.Appleseed!is:a*good&farmer'))``6` (10认同)

Pra*_*mar 11

这是一个不需要导入任何库的单行解决方案.
它用空格替换非字母数字字符(如标点符号),然后split用字符串替换.

灵感来自" 用多个分隔符拆分的Python字符串 "

>>> s = 'Johnny.Appleseed!is:a*good&farmer'
>>> words = ''.join(c if c.isalnum() else ' ' for c in s).split()
>>> words
['Johnny', 'Appleseed', 'is', 'a', 'good', 'farmer']
>>> len(words)
6
Run Code Online (Sandbox Code Playgroud)