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
#1
Hi all, I'm back anyway

The program I wrote is terrible so if anyone can make a different py and give me some pointers well thanks a bunch Wall

What I would like help on is to print only the first two characters of a word and if those same characters repeat hold them to a count. It's like a Zipf distribution but for the first two letters for every word. The example is how I would like the output. Here is an example from this text and its for show!

text file = "Here is an example from this text and its for show!"

an 2
He 1
is 1
ex 1
fr 1
th 1
te 1
it 1
fo 1
sh 1
total 11

file = open("C:\python37\paradise.txt", 'r') 
  
while 1: 
      
    # read by character 
    char = file.read(2)
    if not char:  
        break
          
    print(char) 
  
file.close() 
Reply
#2
cross-posted at StackOverflow
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
@buran,

I had no idea that would be illegal I'm just asking for help of a nice person?
Reply
#4
it's not illegal, but we expect the courtesy to let us know about it. This is valid not only here but basically on any specialized forum. If you don't understand why - read https://meta.stackexchange.com/q/141823
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
@buran
solved at stack-exchange

# dictionary to store count of each word (2 characters) eg. "an": 2
wordDict = {}

file = open("paradise.txt", 'r')
# read each line in file
for line in file:
    # read each word in line
    for word in line.split():
        # get only first two letters of word
        word = word[:2]
        # If word is not in dictionary then add it
        if word not in wordDict:
          wordDict[word] = 1
        # else increment the count
        else:
          wordDict[word] += 1

file.close()

# print all values
for key, val in wordDict.items():
  print(key, val)

# print total
print(f"Total: {sum(wordDict.values())}")
Reply
#6
See- now you already have accepted answer on SO. Any attempt of a member here to help will be a waste of time if we didn't know about cross-posting.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
@buran,

There is a set to solved button and is now checked, relax Huh
Reply
#8
Don't worry, I am relaxed. And you know what to do next time when cross-post, right?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
I tried something as below, see if it helps

file = open('h.txt', 'r') 
   
for each in file: 
    print (each) 
k=each.split()       
###print(k)
j=[]
for i in k:
   ### print(i[:2])
    j.append(i[:2])

###print(j)
result = dict((k, j.count(k)) for k in j)
print(result)
print("total--",sum(result.values()))

file.close()
Output:
h.txt input file: Here is an example from this text and its for show! py g.py Here is an example from this text and its for show! {'He': 1, 'is': 1, 'an': 2, 'ex': 1, 'fr': 1, 'th': 1, 'te': 1, 'it': 1, 'fo': 1, 'sh': 1} total-- 11
Best Regards,
Sandeep

GANGA SANDEEP KUMAR
Reply
#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


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