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
  Print characters in a single line rather than one at a time hhydration 1 216 Oct-10-2020, 10:00 PM
Last Post: bowlofred
  Cannot redirect print to a file tester_V 3 301 Sep-11-2020, 12:21 AM
Last Post: tester_V
  Count & Sort occurrences of text in a file oradba4u 7 307 Sep-06-2020, 03:23 PM
Last Post: oradba4u
  Reading integers from a file; the problem may be the newline characters JRWoodwardMSW 2 379 Jul-14-2020, 02:27 AM
Last Post: bowlofred
  how to count a retransmission packets from pcap file? salwa17 0 293 Jul-04-2020, 11:22 PM
Last Post: salwa17
  Remove escape characters / Unicode characters from string DreamingInsanity 5 958 May-15-2020, 01:37 PM
Last Post: snippsat
  Print/write to file function tpolim008 4 552 Apr-01-2020, 07:59 PM
Last Post: tpolim008
  Print date, Time and output to file tpolim008 3 461 Mar-26-2020, 06:49 PM
Last Post: ndc85430
  Look for match in two files and print out in the first file Batistuta 0 362 Mar-03-2020, 02:27 PM
Last Post: Batistuta
  CSV file escaping characters lokhtar 2 513 Dec-09-2019, 06:48 PM
Last Post: lokhtar

Forum Jump:

User Panel Messages

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