Skip to content

Commit 2ec29ab

Browse files
authored
Merge pull request #1 from geekcomputers/master
try
2 parents 9d91244 + acb6ecb commit 2ec29ab

12 files changed

+231
-49
lines changed

CountMillionCharacter.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -289,8 +289,7 @@
289289
Exeunt'''
290290
count = { }
291291
for character in info.upper():
292-
count.setdefault(character, 0)
293-
count[character] = count[character]+1
292+
count[character]=count.get(character,0)+1
294293

295294
value = pprint.pformat(count)
296295
print(value)

CountMillionCharacters-2.0.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""Get the number of each character in any given text.
2+
3+
Inputs:
4+
A txt file -- You will be asked for an input file. Simply input the name
5+
of the txt file in which you have the desired text.
6+
7+
"""
8+
9+
import pprint
10+
import collections
11+
12+
13+
def main():
14+
15+
file_input = input('File Name: ')
16+
17+
with open(file_input, 'r') as info:
18+
count = collections.Counter(info.read().upper())
19+
20+
value = pprint.pformat(count)
21+
print(value)
22+
23+
if __name__ == "__main__":
24+
main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import pprint
2+
3+
inputFile = input('File Name: ')
4+
5+
count = { }
6+
with open(inputFile, 'r') as info:
7+
readFile = info.read()
8+
for character in readFile.upper():
9+
count.setdefault(character, 0)
10+
count[character] = count[character]+1
11+
12+
value = pprint.pformat(count)
13+
print(value)

README.md

+7-4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
2+
# My Python Examples.
3+
14
Here is some more detailed information about the scripts I have written. I do not consider myself a programmer, I create these little programs as experiments to have a play with the language, or to solve a problem for myself. I would gladly accept pointers from others to improve the code and make it more efficient, or simplify the code. If you would like to make any comments then please feel free to email me at [email protected].
25

36
In the scripts the comments etc are lined up correctly when they are viewed in [Notepad++](https://notepad-plus-plus.org/). This is what I use to code Python scripts.
@@ -18,15 +21,15 @@ In the scripts the comments etc are lined up correctly when they are viewed in [
1821

1922
- `move_files_over_x_days.py` - This will move all the files from the source directory that are over 240 days old to the destination directory.
2023

21-
- `nslookup_check.py` - This very simple script opens the file `server_list.txt` and the does an nslookup for each one to check the DNS entry.
24+
- `nslookup_check.py` - This very simple script opens the file `server_list.txt` and then does an nslookup for each one to check the DNS entry.
2225

2326
- `osinfo.py` - Displays some information about the OS you are running this script on.
2427

25-
- `ping_servers.py` - This script will, depending on the arguments supplied will ping the servers associated with that application group.
28+
- `ping_servers.py` - This script will, depending on the arguments supplied, will ping the servers associated with that application group.
2629

2730
- `ping_subnet.py` - After supplying the first 3 octets it will scan the final range for available addresses.
2831

29-
- `powerdown_startup.py` - This goes through the server list and pings the machine, if it's up it will load the putty session, if its not it will notify you.
32+
- `powerdown_startup.py` - This goes through the server list and pings the machine, if it's up it will load the putty session, if it's not it will notify you.
3033

3134
- `puttylogs.py` - This zips up all the logs in the given directory.
3235

@@ -39,4 +42,4 @@ In the scripts the comments etc are lined up correctly when they are viewed in [
3942
- `serial_scanner.py` contains a method called ListAvailablePorts which returns a list with the names of the serial ports that are in use in our computer, this method works only on Linux and Windows (can be extended for mac osx). If no port is found, an empty list is returned.
4043

4144
- `get_youtube_view.py` - This is very simple python script to get more views for your youtube videos.Some times I use for repeating my favorite songs by this scripts.
42-
- `CountMillionCharacter.py` - This Script will,counting character script count how much character present *any text based file.
45+
- `CountMillionCharacter.py` - This Script will,counting character script, count how much character present *any text based file.

check_file.py

+29-17
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,49 @@
1-
# Script Name : check_file.py
1+
# Script Name : check_file.py
22
# Author : Craig Richards
33
# Created : 20 May 2013
4-
# Last Modified :
4+
# Last Modified :
55
# Version : 1.0
66

77
# Modifications : with statement added to ensure correct file closure
88

99
# Description : Check a file exists and that we can read the file
1010

11+
from __future__ import print_function
1112
import sys # Import the Modules
1213
import os # Import the Modules
1314

14-
# Readfile Functions which open the file that is passed to the script
15+
# Prints usage if not appropriate length of arguments are provided
16+
def usage():
17+
print('[-] Usage: python check_file.py <filename1> [filename2] ... [filenameN]')
18+
exit(0)
19+
1520

21+
# Readfile Functions which open the file that is passed to the script
1622
def readfile(filename):
1723
with open(filename, 'r') as f: # Ensure file is correctly closed under all circumstances
1824
line = f.read()
19-
print line
25+
print(line)
2026

2127
def main():
22-
if len(sys.argv) == 2: # Check the arguments passed to the script
23-
filename = sys.argv[1] # The filename is the first argument
24-
if not os.path.isfile(filename): # Check the File exists
25-
print '[-] ' + filename + ' does not exist.'
26-
exit(0)
27-
if not os.access(filename, os.R_OK): # Check you can read the file
28-
print '[-] ' + filename + ' access denied'
29-
exit(0)
28+
if len(sys.argv) >= 2: # Check the arguments passed to the script
29+
filenames = sys.argv[1:]
30+
for filename in filenames: # Iterate for each filename passed in command line argument
31+
if not os.path.isfile(filename): # Check the File exists
32+
print ('[-] ' + filename + ' does not exist.')
33+
filenames.remove(filename) #remove non existing files from filenames list
34+
continue
35+
36+
if not os.access(filename, os.R_OK): # Check you can read the file
37+
print ('[-] ' + filename + ' access denied')
38+
filenames.remove(filename) # remove non readable filenames
39+
continue
3040
else:
31-
print '[-] Usage: ' + str(sys.argv[0]) + ' <filename>' # Print usage if not all parameters passed/Checked
32-
exit(0)
33-
print '[+] Reading from : ' + filename # Display Message and read the file contents
34-
readfile(filename)
41+
usage() # Print usage if not all parameters passed/Checked
42+
43+
# Read the content of each file
44+
for filename in filenames:
45+
print ('[+] Reading from : ' + filename) # Display Message and read the file contents
46+
readfile(filename)
3547

3648
if __name__ == '__main__':
37-
main()
49+
main()

fileinfo.py

+32-18
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,34 @@
11
# Script Name : fileinfo.py
22
# Author : Not sure where I got this from
33
# Created : 28th November 2011
4-
# Last Modified :
4+
# Last Modified :
55
# Version : 1.0
6-
# Modifications :
6+
# Modifications :
77

88
# Description : Show file information for a given file
99

1010

1111
# get file information using os.stat()
1212
# tested with Python24 vegsaeat 25sep2006
13+
from __future__ import print_function
1314
import os
15+
import sys
1416
import stat # index constants for os.stat()
1517
import time
16-
# pick a file you have ...
17-
file_name = raw_input("Enter a file name: ")
18-
file_stats = os.stat(file_name)
18+
19+
try_count = 16
20+
while try_count:
21+
file_name = raw_input("Enter a file name: ") # pick a file you have ...
22+
try_count >>= 1
23+
try :
24+
file_stats = os.stat(file_name)
25+
break
26+
except OSError:
27+
print ("\nNameError : [%s] No such file or directory\n" %file_name)
28+
29+
if try_count == 0:
30+
print ("Trial limit exceded \nExiting program")
31+
sys.exit()
1932
# create a dictionary to hold file info
2033
file_info = {
2134
'fname': file_name,
@@ -25,23 +38,24 @@
2538
'f_ct': time.strftime("%d/%m/%Y %I:%M:%S %p",time.localtime(file_stats[stat.ST_CTIME]))
2639
}
2740
print
28-
print "file name = %(fname)s" % file_info
29-
print "file size = %(fsize)s bytes" % file_info
30-
print "last modified = %(f_lm)s" % file_info
31-
print "last accessed = %(f_la)s" % file_info
32-
print "creation time = %(f_ct)s" % file_info
41+
print ("file name = %(fname)s" % file_info)
42+
print ("file size = %(fsize)s bytes" % file_info)
43+
print ("last modified = %(f_lm)s" % file_info)
44+
print ("last accessed = %(f_la)s" % file_info)
45+
print ("creation time = %(f_ct)s" % file_info)
3346
print
3447
if stat.S_ISDIR(file_stats[stat.ST_MODE]):
35-
print "This a directory"
48+
print ("This a directory")
3649
else:
37-
print "This is not a directory"
38-
print
39-
print "A closer look at the os.stat(%s) tuple:" % file_name
40-
print file_stats
41-
print
42-
print "The above tuple has the following sequence:"
43-
print """st_mode (protection bits), st_ino (inode number),
50+
print ("This is not a directory")
51+
print ()
52+
print ("A closer look at the os.stat(%s) tuple:" % file_name)
53+
print (file_stats)
54+
print ()
55+
print ("The above tuple has the following sequence:")
56+
print ("""st_mode (protection bits), st_ino (inode number),
4457
st_dev (device), st_nlink (number of hard links),
4558
st_uid (user ID of owner), st_gid (group ID of owner),
4659
st_size (file size, bytes), st_atime (last access time, seconds since epoch),
4760
st_mtime (last modification time), st_ctime (time of creation, Windows)"""
61+
)

folder_size.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,9 @@
2121
filename = os.path.join(path, file)
2222
dir_size += os.path.getsize(filename) # Add the size of each file in the root dir to get the total size.
2323

24-
for key in fsizedicr: #iterating through the dictionary
25-
print ("Folder Size: " + str(round(fsizedicr[key]*dir_size, 2)) + " " + key) # round function example: round(4.2384, 2) ==> 4.23
24+
fsizeList = [str(round(fsizedicr[key]*dir_size, 2)) + " " + key for key in fsizedicr] # List of units
25+
26+
if dir_size == 0: print ("File Empty") # Sanity check to eliminate corner-case of empty file.
27+
else:
28+
for units in sorted(fsizeList)[::-1]: # Reverse sort list of units so smallest magnitude units print first.
29+
print ("Folder Size: " + units)

get_youtube_view.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22
import webbrowser
33

44
#how much views you want
5-
5+
#This only works when video has less than 300 views, it won't work when there are more than 300 views...
6+
#due to youtube's policy.
67
print("Enjoy your Time\n" +time.ctime())
78
for count in range(30):
8-
time.sleep(5)
9+
time.sleep(5)
910
webbrowser.open("https://www.youtube.com/watch?v=o6A7nf3IeeA")

jee_result.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import mechanize
2+
from bs4 import BeautifulSoup
3+
import urllib2
4+
# Create a Browser
5+
b = mechanize.Browser()
6+
7+
# Disable loading robots.txt
8+
b.set_handle_robots(False)
9+
10+
b.addheaders = [('User-agent',
11+
'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98;)')]
12+
13+
# Navigate
14+
b.open('http://cbseresults.nic.in/jee/jee_2015.htm')
15+
16+
# Choose a form
17+
b.select_form(nr=0)
18+
19+
# Fill it out
20+
b['regno'] = '37000304'
21+
22+
import datetime
23+
currentdate = datetime.date(1997,3,10)
24+
enddate = datetime.date(1998,4,1)
25+
while currentdate <= enddate:
26+
ct=0
27+
#print currentdate
28+
yyyymmdd=currentdate.strftime("%Y/%m/%d")
29+
ddmmyyyy=yyyymmdd[8:]+"/"+yyyymmdd[5:7]+"/"+yyyymmdd[:4]
30+
print(ddmmyyyy)
31+
b.open('http://cbseresults.nic.in/jee/jee_2015.htm')
32+
b.select_form(nr=0)
33+
b['regno'] = '37000304'
34+
b['dob']=ddmmyyyy
35+
36+
fd = b.submit()
37+
#print(fd.read())
38+
soup = BeautifulSoup(fd.read(),'html.parser')
39+
40+
for writ in soup.find_all('table'):
41+
ct=ct+1;
42+
#print (ct)
43+
if ct==6:
44+
print("---fail---")
45+
else:
46+
print("--true--")
47+
break;
48+
currentdate += datetime.timedelta(days=1)
49+
#print fd.read()

movie_details

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import mechanize
2+
from bs4 import BeautifulSoup
3+
import urllib2
4+
# Create a Browser
5+
b = mechanize.Browser()
6+
7+
# Disable loading robots.txt
8+
b.set_handle_robots(False)
9+
10+
b.addheaders = [('User-agent',
11+
'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98;)')]
12+
nm=raw_input("enter title ")
13+
# Navigate
14+
b.open('http://www.imdb.com/search/title')
15+
16+
# Choose a form
17+
b.select_form(nr=1)
18+
19+
20+
b['title'] = nm
21+
22+
b.find_control(type="checkbox",nr=0).get("feature").selected = True
23+
24+
25+
# Submit
26+
fd = b.submit()
27+
28+
soup = BeautifulSoup(fd.read(),'html5lib')
29+
30+
#data= soup.find_all('td',class_="title")
31+
#for div in data:
32+
# links= div.find_all('a')
33+
# for a in links:
34+
# print a['href'];
35+
36+
37+
for div in soup.findAll('td', {'class': 'title'},limit=1):
38+
a = div.findAll('a')[0]
39+
print a.text.strip(), '=>', a.attrs['href']
40+
hht='http://www.imdb.com'+a.attrs['href']
41+
print(hht)
42+
page=urllib2.urlopen(hht)
43+
soup2 = BeautifulSoup(page.read(),'html.parser')
44+
print("title of the movie: ")
45+
print(soup2.find(itemprop="name").get_text())
46+
print("timerun: ")
47+
print(soup2.find(itemprop="duration").get_text())
48+
print("genre: ")
49+
print(soup2.find(itemprop="genre").get_text())
50+
print("current IMDB rating:")
51+
print(soup2.find(itemprop="ratingValue").get_text())
52+
print("summary:")
53+
print(soup2.find(itemprop="description").get_text())

osinfo.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,19 @@
3030
'version',
3131
]
3232

33+
class bcolors:
34+
HEADER = '\033[95m'
35+
OKBLUE = '\033[94m'
36+
OKGREEN = '\033[92m'
37+
WARNING = '\033[93m'
38+
FAIL = '\033[91m'
39+
ENDC = '\033[0m'
40+
BOLD = '\033[1m'
41+
UNDERLINE = '\033[4m'
42+
3343

3444

3545
for key in profile:
3646
if hasattr(pl,key):
37-
print(key + ": "+ str(getattr(pl,key)()))
47+
print(key + bcolors.BOLD + ": "+ str(getattr(pl,key)())+ bcolors.ENDC)
3848

testlines.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@
99
# Description : This very simple script open a file and prints out 100 lines of whatever is set for the line variableest you want to print\n" # This sets the variable for the text that you want to print
1010

1111

12-
def write_to_file(filename,txt):
13-
with open(filename,'w') as file_object:
12+
def write_to_file(filename, txt):
13+
with open(filename, 'w') as file_object:
1414
s = file_object.write(txt)
1515

1616

1717
if __name__ == '__main__':
18-
write_to_file('test.txt', 'i am beven')
18+
write_to_file('test.txt', 'I am beven')
1919

0 commit comments

Comments
 (0)