Python Forum
get two characters, count and print from a .txt file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
get two characters, count and print from a .txt file
#10
There is ambiguity in this task. What should happen if 'a' encountered (totally realistic scenario in english)? Also, should 'he' and 'He' be considered as different?

This solution is needlessly complicated. As mentioned in SO post there is Counter in collections built-in module which is specifically for counting. So code can be as simple as 'count two first letters of word for every word on every line':

from collections import Counter

# Content of the file: Here is an example from this text and its for show!

with open('two_chars_count.csv', 'r') as f:
    count = Counter(word[:2].lower() for line in f for word in line.split())

print(*(f'{k}: {v}' for k, v in count.items()), sep='\n')

he: 1
is: 1
an: 2
ex: 1
fr: 1
th: 1
te: 1
it: 1
fo: 1
sh: 1
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
RE: get two characters, count and print from a .txt file - by perfringo - Oct-05-2020, 09:22 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Row Count and coloumn count Yegor123 4 1,331 Oct-18-2022, 03:52 AM
Last Post: Yegor123
  Saving the print result in a text file Calli 8 1,799 Sep-25-2022, 06:38 PM
Last Post: snippsat
  failing to print not matched lines from second file tester_V 14 6,093 Apr-05-2022, 11:56 AM
Last Post: codinglearner
  Print to a New Line when Appending File DaveG 0 1,225 Mar-30-2022, 04:14 AM
Last Post: DaveG
Sad Want to Save Print output in csv file Rasedul 5 10,980 Jan-11-2022, 07:04 PM
Last Post: snippsat
  Convert legacy print file to XLSX file davidm 1 1,812 Oct-17-2021, 05:08 AM
Last Post: davidm
  Why it does not print(file.read()) Rejaul84 1 2,346 Jul-01-2021, 10:37 PM
Last Post: bowlofred
  all i want to do is count the lines in each file Skaperen 13 4,841 May-23-2021, 11:24 PM
Last Post: Skaperen
  Split Characters As Lines in File quest_ 3 2,525 Dec-28-2020, 09:31 AM
Last Post: quest_
  How to use the count function from an Excel file using Python? jpy 2 4,463 Dec-21-2020, 12:30 AM
Last Post: jpy

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020