python - Counting number of words, characters, and lines of a given .txt file using PyCharm - Stack Overflow

I am currently struggling to find the number of words, characters, and lines of a song in a lyrics.txt

I am currently struggling to find the number of words, characters, and lines of a song in a lyrics.txt file. I was able to find number of words and lines only, but the two code blocks I have for finding this out, doesn't work.

Here's my current code so far:

count = 0
infile = open('lyrics.txt')

for line in infile:
    count = count + 1
print("The song has about", count, "lines in total.")

data = infile.read()
wordCount = len(data)
print("Love Me Harder has approximately", wordCount, "total words in the song.")

I am currently struggling to find the number of words, characters, and lines of a song in a lyrics.txt file. I was able to find number of words and lines only, but the two code blocks I have for finding this out, doesn't work.

Here's my current code so far:

count = 0
infile = open('lyrics.txt')

for line in infile:
    count = count + 1
print("The song has about", count, "lines in total.")

data = infile.read()
wordCount = len(data)
print("Love Me Harder has approximately", wordCount, "total words in the song.")
Share Improve this question asked 12 hours ago UnusualAce77UnusualAce77 617 bronze badges New contributor UnusualAce77 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 2
  • This question is similar to: Counting lines, words, and characters within a text file using Python. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – JonSG Commented 12 hours ago
  • on Linux I would use program wc in console: wc lyrics.txt – furas Commented 11 hours ago
Add a comment  | 

1 Answer 1

Reset to default 1

You can only "read" a file once. You are at the end of the file when you do `infile.read()`, so nothing is read.

You either have to re-open the file or call `infile.seek(0)` to force it back to the beginning of the file.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743752432a4501147.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信