簡體   English   中英

試圖計算字符串中的單詞

[英]Trying to count words in a string

我正在嘗試分析字符串的內容。 如果它在單詞中混合了標點符號,我想用空格替換它們。

例如,如果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))

簡單循環解決方案:

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']

更好的方案:

使用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']

這是一個不需要導入任何庫的單行解決方案。
它用空格替換非字母數字字符(如標點符號),然后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

試試這個:它使用re解析word_list,然后創建一個單詞詞典:appearances

import re
word_list = re.findall(r"[\w']+", string)
print {word:word_list.count(word) for word in word_list}

如何使用收藏品中的Counter?

import re
from collections import Counter

words = re.findall(r'\w+', string)
print (Counter(words))
for ltr in ('!', '.', ...) # insert rest of punctuation
     stringss = strings.replace(ltr, ' ')
return len(stringss.split(' '))

我知道這是一個古老的問題,但是......這個怎么樣?

string = "If Johnny.Appleseed!is:a*good&farmer"

a = ["*",":",".","!",",","&"," "]
new_string = ""

for i in string:
   if i not in a:
      new_string += i
   else:
      new_string = new_string  + " "

print(len(new_string.split(" ")))
#Write a python script to count words in a given string.
 s=str(input("Enter a string: "))
 words=s.split()
 count=0
  for word in words:
      count+=1

  print(f"total number of words in the string is : {count}")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM