Ich versuche, den Inhalt einer Zeichenfolge zu analysieren. Wenn es eine Interpunktion im Wort enthält, möchte ich sie durch Leerzeichen ersetzen.
Wenn zum Beispiel Johnny.Appleseed! Ist: Ein * good & farmer wird als Eingabe eingegeben, dann sollte es sagen, dass es 6 Wörter gibt, aber mein Code sieht nur 0 Wörter. Ich bin nicht sicher, wie man ein falsches Zeichen entfernt.
Zu Ihrer Information: Ich benutze Python 3, ich kann auch keine Bibliotheken importieren
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
verwenden:
>>> 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']
Hier ist eine einzeilige Lösung, bei der keine Bibliotheken importiert werden müssen.
Er ersetzt nicht alphanumerische Zeichen (wie Interpunktion) durch Leerzeichen und split
s die Zeichenfolge.
Inspiriert von " Python-Strings, die mit mehreren Trennzeichen geteilt werden "
>>> 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
probieren Sie folgendes aus: Es analysiert die Word-Liste mit re und erstellt dann ein Wörterbuch mit Word-Erscheinungsbildern
import re
Word_list = re.findall(r"[\w']+", string)
print {Word:word_list.count(Word) for Word in Word_list}
Wie wäre es mit Counter aus Sammlungen?
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(' '))
Ich weiß, dass dies eine alte Frage ist, aber ... Wie wäre es damit?
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}")