473,395 Members | 1,442 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

[Python] Read .txt file and analayze

Hello all;

I'm working huffman coding of any .txt file, so first I need to analyse this text file. I need to read it, then analyse.
I need "exit" like table:
****************************
letter frequency(how many times same latter repeated) Huffman code(this will come later)

************************

I started with:
Expand|Select|Wrap|Line Numbers
  1. f = open('test.txt', 'r')    #open test.tx
  2.     for lines in f:
  3.         print lines          #to ensure if all work...
  4.  
Can anyone help me?
Dec 4 '10 #1
4 3041
Expand|Select|Wrap|Line Numbers
  1. def countLetters(line, letter):
  2.     ret = 0
  3.     for character in line:
  4.         if character == letter: ret += 1
  5.     return ret
  6.  
  7. for line in open("file.txt"):
  8.     line = line.strip()
  9.     print line
  10.     print "Has", countLetters(line, "a"), "of letter a."
  11.     print "Has", countLetters(line, "e"), "of letter e."
  12.     print "Has", countLetters(line, "i"), "of letter i."
  13.     print "Has", countLetters(line, "o"), "of letter o."
  14.     print "Has", countLetters(line, "u"), "of letter u."
  15.     print "Has", countLetters(line, "y"), "of letter y."
  16.     print
Dec 5 '10 #2
twohot
8
Modifying Sean's Code:

Expand|Select|Wrap|Line Numbers
  1. #!/bin/python3
  2.  
  3. def countLetters(line, letter):
  4.    ret = 0
  5.    for character in line:
  6.       if character == letter: ret += 1
  7.    return ret
  8.  
  9. alphabet = 'abcdefghijklmnopqrstuvwxyz'
  10. #you can automate this using ascii codes too
  11.  
  12. for line in open("file.txt",'r'):
  13.    line = line.strip() #remove trailing spaces
  14.    print (line)
  15.    for letter in alphabet:
  16.       print ('Has {0} of letter {1}'.\
  17.       format(str(countLetters(line,letter)),letter))

output:

gbfchjwshfcjkwhndfnxh;iquw;qemiziqmeuzngyegbfyewgy bqgzeqzydglndhlqhd;jkjnenjcejnrcjercbvvbdbggngnjmm nmsnvsdmsnfsfcsf>mNmvbmsdbfluaheregnctfbaxzmasqojm wqi;htrugttgp
Has 3 of letter a
Has 9 of letter b
Has 7 of letter c
Has 7 of letter d
Has 10 of letter e
Has 9 of letter f
Has 12 of letter g
Has 8 of letter h
Has 4 of letter i
Has 9 of letter j
Has 2 of letter k
Has 3 of letter l
Has 11 of letter m
Has 13 of letter n
Has 1 of letter o
Has 1 of letter p
Has 8 of letter q
Has 4 of letter r
Has 8 of letter s
Has 4 of letter t
Has 4 of letter u
Has 4 of letter v
Has 5 of letter w
Has 2 of letter x
Has 4 of letter y
Has 5 of letter z
Dec 27 '10 #3
Expand|Select|Wrap|Line Numbers
  1. #-------------------------------------------------#
  2. # Set Variables                                   #
  3. #-------------------------------------------------#
  4.  
  5. input = open("file.txt")
  6. whitelist = ('a','b','c','d','e','f','g') # whitelist of letters
  7. letters = {}
  8.  
  9. #-------------------------------------------------#
  10. #  Functions                                      #
  11. #-------------------------------------------------#
  12.  
  13. def count_letter(c):
  14.   if c in letters:
  15.     letters[c] += 1  # if letter in letters add one
  16.   else:
  17.     letters[c] = 1   # if letter not in letters set add letter to dictionary object
  18.  
  19.  
  20. def print_letters(letters):
  21.  
  22.   for k,v in letters.items():
  23.     if k in whitelist:
  24.       print "Has %s of letter %s" % (v,k) # print out count for each letter
  25.  
  26.  
  27. #-------------------------------------------------#
  28. #  Run code                                       #
  29. #-------------------------------------------------#
  30.  
  31.  
  32. for line in input:          # for each line in input file
  33.   for letter in line:       # for each letter in line
  34.     count_letter(letter)    # tally a count of each letter
  35.  
  36. print_letters(letters)
  37.  
Here I use a more pythonic syntax, which means less lines of code. If you count everything and whitelist the characters your concerned with then your code can be easily modified in the future.

Hope this helps!
Dec 31 '10 #4
twohot
8
Very neat Michael
Dec 31 '10 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

40
by: Abby | last post by:
My .dat file will contain information like below. /////////// First 0x04 0x05 0x06 Second 0x07
0
by: py | last post by:
i need to read the contents of a file (could be 100kb, could be 500mb, could be 1gb)...but I want to allow the read to be canceled. for example, say a user wants to savea file...as it's saving...
2
by: pycircle | last post by:
From a python module, I want to run any.py module, to open it in the shell, just like if I were in IDLE editor and selecting EDIT / Run Module. I have tried a lot of things, including importing a...
2
by: somequestion | last post by:
During copying file , wanna read file Size like this string CheckFileSize(string fileName) { if( fileName == null ) return; FileInfo fi = new FileInfo(fileName); return fi.Length.ToString();...
1
by: potluri040 | last post by:
hi, could any one let me know how to read file thru VB script. Scenerio is like this: i am keeping a personal details such as name, age, sex, company, location in a text file called user details...
2
by: yinglcs | last post by:
How to modify the source of a python file inside a python egg file? I can see the file by unzipping it, but how can I package it back as a python egg file after my modification. Thank you.
3
by: =?Utf-8?B?Sm9obiBXYWxrZXI=?= | last post by:
Hi, Is there anything wrong with the code below in sending my browser page to Excel? Before my page opens in Excel there's a message "Problems came up in the following areas during load:" and it...
2
by: yinglcs | last post by:
Hi, I am trying to use python for file processing. Suppose I have a file like this: I want to build a Hashmap between the line "begin_QOS_statistics" and "end_QOS_statistics" and for each line...
2
by: xplode144 | last post by:
I have a Web application. i need to read a file once during the startup and preserve the read data throughout the life of the application. i will to access the data often during the page_load of...
2
by: danimian | last post by:
Hello, first i am creating xml file if file does not exist. String myFile = "C:\myxmlfile.xml"; if (!File.Exists(myFile)) { using (FileStream conStream = new FileStream(myFile,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.