Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

문자열에서 단어의 발생 횟수를 계산하는 Python 프로그램

<시간/>

이 튜토리얼에서는 문자열에서 단어가 나오는 횟수를 세는 프로그램을 작성할 것입니다. 단어와 문자열이 주어지면 문자열에서 단어의 빈도를 계산해야 합니다.

나는 프로그래머입니다. 저는 학생입니다. 그리고 이다라는 단어는 . 우리가 작성할 프로그램은 숫자 2를 반환합니다. 단어 발생으로 문자열에서 두 번.

목표를 달성하기 위해 다음 단계를 따르십시오.

알고리즘

1. Initialize the string and the word as two variables.
2. Split the string at spaces using the split() method. We will get a list of words.
3. Initialize a variable count to zero.
4. Iterate over the list.
4.1. Check whether the word in the list is equal to the given the word or not.
4.1.1. Increment the count if the two words are matched.
5. Print the count.

먼저 프로그램에 대한 코드를 직접 작성해 보십시오. 코드를 봅시다.

예시

## initializing the string and the word
string = "I am programmer. I am student."
word = "am"
## splitting the string at space
words = string.split()
## initializing count variable to 0
count = 0
## iterating over the list
for w in words:
   ## checking the match of the words
   if w == word:
      ## incrementint count on match
      count += 1
## printing the count
print(count)

출력

위의 프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다.

2

결론

프로그램에 대해 궁금한 점이 있으면 댓글 섹션에서 질문하세요.