Python Experimental Project 6: File Operation and Modularization

1. Use the random library to generate 10 random numbers between 100 and 200, and find their maximum value, mean, standard deviation and median.

# 1. Use the random library to generate 10 random numbers between 100 and 200, and find their maximum value, average value, standard deviation and median.
import random
# define a list
list=[]
for i in range(10):
    list.insert(i,random.randint(100, 200))
max=list[0]
sum=0# Sum
avg=0# average value
std=0# standard deviation
mid=0# median
for i in range(10):
    if max<list[i]:
        max=list[i]
    sum + =list[i]
avg=sum/10
list.sort()
mid=list[5]
std=0
for i in range(10):
    std + =(list[i]-avg)**2
    std=std/10
std=std**0.5
print(f"The maximum value is: {max}")
print(f"The average value is: {avg}")
print(f"The standard deviation is: {std}")
print(f"The median is: {mid}")

2. Convert all English letters in one file to uppercase and copy them to another file.

# 2. Convert all English letters in one file to uppercase and copy them to another file.
f=open("a.txt","r")
read = f.read()
f.close()
read = read.upper()
f=open("b.txt","w")
f.write(read)
f.close()

3. Chinese text analysis and statistics.

Requirement: Given a document “wind.txt”, count the top 3 words and their occurrences frequency.

Tip: Chinese text analysis and statistics usually involve file operations with third-party libraries such as jieba, dictionaries, lists, etc. Knowledge points are combined together, and the focus is on the ability to comprehensively apply knowledge.

(1) Import the third-party library jieba library, which is used for Chinese word segmentation.

(2) Use the default encoding method of the current operating system, open the text file “wind.txt”, and copy The contents of the file are read into the variable txt.

(3) Use the lcut() method of the jieba library to segment the txt variable into words, and save the word segmentation results to the list ls.

(4) Complete the word frequency statistics function and save it in the dictionary; save the statistical results in the dictionary to a list freq_word, then sort according to the frequency of occurrence, and finally output .

# 3. Chinese text analysis and statistics.
# Requirement: Given a document "wind.txt", count the top 3 words with the highest word frequency and their number of occurrences.
# Tip: Chinese text analysis and statistics usually combine file operations with knowledge points such as third-party libraries jieba libraries, dictionaries, lists, etc. The focus is on the ability to comprehensively apply knowledge.
# (1) Import the third-party library jieba library, which is used for Chinese word segmentation.
# (2) Using the default encoding method of the current operating system, open the text file "wind.txt" and read the file content into the variable txt.
# (3) Use the lcut() method of the jieba library to segment the txt variable into words, and save the word segmentation results to the list ls.
# (4) Complete the word frequency statistics function and save it in the dictionary; save the statistical results in the dictionary into the list freq_word, then sort according to the frequency of occurrence, and finally output.
import jieba
f=open("wind.txt","r",encoding="utf-8")
text=f.read()
f.close()
for item in ',. ! ?,;\\
: ""': #Because the String class is immutable, that is, once a String object is created, its value cannot be changed. Therefore, when the replace method is called, it does not change the original string, but returns a new string. Therefore, the returned new string needs to be assigned to the original string variable to implement the replacement operation.
    text=text.replace(item, "")
print(text)
ls=jieba.lcut(text)
dic={}
for i in ls:
    if i in dic:
        dic[i] + =1
    else:
        dic[i]=1
freq_word=sorted(dic.items(),key=lambda x:x[1],reverse=True)
print(freq_word[:3])

4. Delete the specified word in one file and copy it to another file.

# 4. Delete the specified word in one file and copy it to another file.
f=open("a.txt","r")
read = f.read()
f.close()
replace = read.replace("a", "")
f=open("b.txt","w")
f.write(replace)# What is passed is replace, not read.
f.close()

5. Receive a file name input by the user from the keyboard, and then determine whether the file exists in the current directory. If it exists, the following information is output: whether the file is readable and writable, the size of the file, and whether the file is an ordinary file or a directory.

# 5. Receive a file name input by the user from the keyboard, and then determine whether the file exists in the current directory.
# If it exists, output the following information: whether the file is readable and writable, the size of the file, and whether the file is an ordinary file or a directory.
file_name = input("Please enter the file name:")
try:
    file = open(file_name, "r")
    print("Is the file readable:", file.readable())
    print("Is the file writable:", file.writable())
    print("Size of file:", file.tell())
    if(file.isatty()):
        print("The file is a directory")
    else:
        print("The file is an ordinary file")
    file.close()
except:
    print("The file does not exist!")

6. Encrypt a text file and output it. The rules are as follows: uppercase English characters A are transformed into C, B is transformed into D, …, and Y is transformed into A, Z. Convert to B, the rules for lowercase English characters are the same as above, and other characters remain unchanged.

# 6. Encrypt a text file and output it. The rules are as follows: uppercase English characters A are transformed into C, B is transformed into D,..., Y is transformed into A, Z is transformed into B. The rules for lowercase English characters are the same as above, and other rules are the same. Characters remain unchanged.
f=open('a.txt','r')
f_read = f.read()
print(f"Before encryption: {f_read}")
f1=open('b.txt','w')
for i in f_read:
    if i.isupper():
        if i == 'Y':
            f_read = f_read.replace(i,'A')
        elif i == 'Z':
            f_read = f_read.replace(i, 'B')
        else:
            f_read = f_read.replace(i,chr(ord(i) + 2))
    elif i.islower():
        if i == 'y':
            f_read = f_read.replace(i, 'a')
        elif i == 'z':
            f_read = f_read.replace(i, 'b')
        else:
            f_read = f_read.replace(i, chr(ord(i) + 2))
f.close()
f1.write(f_read)
f1.close()
print('Encryption successful!')
f1=open('b.txt','r')
psw = f1.read()
print(f"After encryption: {psw}")

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeAdvanced grammarFile 388219 people are learning the system