code

숫자, 구두점 및 공백을 무시하고 문장의 단어 수를 계산하는 방법은 무엇입니까?

codestyles 2021. 1. 10. 17:16
반응형

숫자, 구두점 및 공백을 무시하고 문장의 단어 수를 계산하는 방법은 무엇입니까?


문장에서 단어를 세는 방법은 무엇입니까? 저는 파이썬을 사용하고 있습니다.

예를 들어 다음과 같은 문자열이있을 수 있습니다.

string = "I     am having  a   very  nice  23!@$      day. "

7 단어입니다. 각 단어 전후 및 숫자 또는 기호가 관련된 경우 임의의 공백 수에 문제가 있습니다.


str.split() 인수없이 공백 문자 실행시 분할됩니다.

>>> s = 'I am having a very nice day.'
>>> 
>>> len(s.split())
7

링크 된 문서에서 :

경우 9월가 지정되지 않았거나 None연속적인 공백의 실행은 하나의 구분으로 간주하고, 문자열이 선행 또는 후행 공백 경우 결과는 시작 또는 끝 부분에 빈 문자열을 포함하지 않습니다 : 다른 분할 알고리즘이 적용됩니다.


다음을 사용할 수 있습니다 regex.findall().

import re
line = " I am having a very nice day."
count = len(re.findall(r'\w+', line))
print (count)

정규식을 사용하는 간단한 단어 카운터입니다. 스크립트에는 완료되면 종료 할 수있는 루프가 포함되어 있습니다.

#word counter using regex
import re
while True:
    string =raw_input("Enter the string: ")
    count = len(re.findall("[a-zA-Z_]+", string))
    if line == "Done": #command to terminate the loop
        break
    print (count)
print ("Terminated")

s = "I     am having  a   very  nice  23!@$      day. "
sum([i.strip(string.punctuation).isalpha() for i in s.split()])

위의 문장은 청크가 실제로 알파벳 문자열인지 확인하기 전에 각 텍스트 청크를 살펴보고 구두점을 제거합니다.


좋아, 여기 내 버전이 있습니다. 나는 당신이 당신의 출력을 원한다는 것을 알아 챘 7는데, 이것은 당신이 특수 문자와 숫자를 계산 하고 싶지 않다는 것을 의미합니다. 그래서 여기 정규식 패턴이 있습니다 :

re.findall("[a-zA-Z_]+", string)

여기서는 beetwen (소문자) 및 ( 대문자) 모든 문자 [a-zA-Z_]와 일치 함을 의미합니다 .a-zA-Z


공간에 대해. 모든 추가 공백을 제거하려면 다음을 수행하십시오.

string = string.rstrip().lstrip() # Remove all extra spaces at the start and at the end of the string
while "  " in string: # While  there are 2 spaces beetwen words in our string...
    string = string.replace("  ", " ") # ... replace them by one space!

간단한 루프를 사용하여 공백 수를 세는 것은 어떻습니까!?

txt = "Just an example here move along" 
count = 1
for i in txt:
if i == " ":
   count += 1
print(count)


    def wordCount(mystring):  
        tempcount = 0  
        count = 1  

        try:  
            for character in mystring:  
                if character == " ":  
                    tempcount +=1  
                    if tempcount ==1:  
                        count +=1  

                    else:  
                        tempcount +=1
                 else:
                     tempcount=0

             return count  

         except Exception:  
             error = "Not a string"  
             return error  

    mystring = "I   am having   a    very nice 23!@$      day."           

    print(wordCount(mystring))  

출력은 8입니다.


import string 

sentence = "I     am having  a   very  nice  23!@$      day. "
# Remove all punctuations
sentence = sentence.translate(str.maketrans('', '', string.punctuation))
# Remove all numbers"
sentence = ''.join([word for word in sentence if not word.isdigit()])
count = 0;
for index in range(len(sentence)-1) :
    if sentence[index+1].isspace() and not sentence[index].isspace():
        count += 1 
print(count)

ReferenceURL : https://stackoverflow.com/questions/19410018/how-to-count-the-number-of-words-in-a-sentence-ignoring-numbers-punctuation-an

반응형