最新要闻

广告

手机

iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?

iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?

警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案

警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案

家电

世界观速讯丨9 文件操作

来源:博客园


(资料图片)

  1. 生成50个MAC地址并写入文件mac.txt中,MAC地址前6位(16进制)为4A-3F-56。
    1 import random 2 import string 3  4  5 # 随机生成一个mac地址 6 def create_mac(): 7     MAC = "01-AF-3B" 8     hex_num = string.hexdigits 9     for i in range(3):10         n = random.sample(hex_num, 2)11         sn = "-" + "".join(n).upper()12         MAC += sn13     return MAC14 15 16 # print(create_mac())17 18 # 随机生成50个MAC 地址19 def main():20     with open("mac.txt", "w") as f:21         for i in range(50):22             mac = create_mac()23             print(mac)24             # 每生成一个MAC地址,存入文件25             f.write(mac + "\n")26 27 28 main()29 30 31 32 def count(s):33   alpha,num,space,other=0,0,0,034   for i in s:35     if i.isalpha():36         alpha+=137     elif i.isdigit():38         num+=139     elif i.isspace():40         space+=141     else:42         other+=143   print("英文字符数{},数字字符数{},空格字符数{},其他字符数{}".format(alpha,num,space,other))44 count(input("请输入一个字符串:"))

    输出结果:

    1 "C:\Program Files\Python39\python.exe" E:/课件/python/作业10/1随机生成MAC地址/MAC地址.py  2 01-AF-3B-8B-D2-90 3 01-AF-3B-6F-FE-C0 4 01-AF-3B-A3-CB-F8 5 01-AF-3B-D8-AD-28 6 01-AF-3B-B4-56-73 7 01-AF-3B-BA-39-CB 8 01-AF-3B-B2-12-BA 9 01-AF-3B-47-6B-BA10 01-AF-3B-A4-C4-B511 01-AF-3B-F4-F3-0712 01-AF-3B-AE-AF-F913 01-AF-3B-5C-6A-A914 01-AF-3B-CA-0B-D615 01-AF-3B-40-A9-0216 01-AF-3B-B6-75-5A17 01-AF-3B-AD-A4-B618 01-AF-3B-9C-31-DF19 01-AF-3B-D8-3C-BC20 01-AF-3B-CB-F2-2A21 01-AF-3B-DE-21-1B22 01-AF-3B-AB-C0-C123 01-AF-3B-2F-5A-DB24 01-AF-3B-02-0A-FF25 01-AF-3B-D7-AC-E226 01-AF-3B-A2-CA-8A27 01-AF-3B-FE-8F-EA28 01-AF-3B-7B-FB-B029 01-AF-3B-EF-CF-B230 01-AF-3B-CB-52-6F31 01-AF-3B-F9-2F-FA32 01-AF-3B-54-6A-C233 01-AF-3B-F4-FB-DB34 01-AF-3B-CE-9E-0B35 01-AF-3B-7D-D0-A636 01-AF-3B-53-CA-FD37 01-AF-3B-7C-C1-B838 01-AF-3B-87-AB-6E39 01-AF-3B-13-E6-5B40 01-AF-3B-E7-AF-6441 01-AF-3B-8F-8E-E342 01-AF-3B-10-FA-3E43 01-AF-3B-59-B5-C344 01-AF-3B-BF-E1-CF45 01-AF-3B-40-CD-5946 01-AF-3B-AD-B4-7547 01-AF-3B-FC-A8-7D48 01-AF-3B-68-1C-AC49 01-AF-3B-56-DE-4F50 01-AF-3B-4E-9B-AB51 01-AF-3B-FC-80-65
  2. 读取文本文件ABC中的内容,统计其频率最高的10个单词,将结果写入CSV文件中。
    1 import re 2 import csv 3  4  5 def order_dict(dicts, n): 6     result = [] 7     result1 = [] 8     p = sorted([(k, v) for k, v in dicts.items()], reverse=True) 9     s = set()10     for i in p:11         s.add(i[1])12     for i in sorted(s, reverse=True)[:n]:13         for j in p:14             if j[1] == i:15                 result.append(j)16     for r in result:17         result1.append(r[0])18 19     return result120 21 22 def order_dict1(dicts, n):  # 截取排序结果想要的部分返回23     list1 = sorted(dicts.items(), key=lambda x: x[1])24 25     return list1[-1:-(n + 1):-1]26     # return list1[-2:-(n+2):-1]   #去除统计结果为""的情况(前面步骤中,字典没有提前""去掉的情况下)27 28 29 if __name__ == "__main__":30     # 1 获取文本31     f = open("ABC.txt", "r", encoding="UTF-8")32     txt = f.read()33     txt = txt.lower()  # 将所有字符转换为小写34     f.close()35 36     # 2 划分单词37     array = re.split("[ ,.\n]", txt)38     # print("分词结果",array)39 40     # 3 词频统计41     dic = {}42     for i in array:43         if i not in dic:44             dic[i] = 145         else:46             dic[i] += 147     # 4 除掉无价值的词48     del [dic[""]]49 50     # 5 输出出现频率最高的10个单词51     print("\n")52     print(order_dict1(dic, 10), )53 # -*- coding: utf-8 -*-54 55 # 统计其频率最高的10个单词,将结果写入CSV文件中56 with open("统计结果.csv", "a", newline="") as f:57     writer = csv.writer(f)58 59     writer.writerow(["word", "amount"])60 61     row = [("to", 6), ("or", 4), ("her", 4), ("your", 4), ("you", 3), ("at", 3), ("say", 3), ("in", 3), ("trouble", 3),62            ("try", 2)]63 64     for r in row:65         writer.writerow(r)
    输出结果:
    1 输出出现频率最高的10个单词2 [("to", 6), ("or", 4), ("her", 4), ("your", 4), ("you", 3), ("at", 3), ("say", 3), ("in", 3), ("trouble", 3), ("try", 2)]
    ABC.txt 文本内容如下
    Parents often get angry because of their trouble in their lives. Let"s say that your mother is not happy about her boss. If she doesn"t have other ways of expressing her emotions, she might come home and yell at you, scream at your dad, kick at the dog, or even say something mean to you.www.xiao84.comHere"s how to handle it when an adult in your life has trouble controlling his or her anger: Don"t make it worse. Angry people can have trouble thinking clearly, so try not to do or say anything to make things worse. Wait till your parent cools off, then talk to him or her in a calm tone, and try to explain how the anger is affecting you.

    #代码参考(Python实现文本词频统计——读取英文文本进行词频统计并输出)

    https://blog.csdn.net/qq_41618424/article/details/104721775

    python写入数据到csv或xlsx文件的3种方法

    https://huaweicloud.csdn.net/63803d64dacf622b8df86a5f.html?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2~default~YuanLiJiHua~activity-3-127619383-blog-104603320.pc_relevant_3mothn_strategy_and_data_recovery&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~YuanLiJiHua~activity-3-127619383-blog-104603320.pc_relevant_3mothn_strategy_and_data_recovery&utm_relevant_index=4

  3. 编码将文件JsonData文件中数据,按如下图所示格式的数据输出。
    1 Data = [{ 2     "ID": 1, 3     "Name": "张永华", 4     "Sex": "男", 5     "Score": 92.7 6 }, 7     { 8         "ID": 2, 9         "Name": "Test",10         "Sex": "女",11         "Score": 91.312     },13     {14         "ID": 3,15         "Name": "DingY",16         "Sex": "男",17         "Score": 95.618     },19     {20         "ID": 4,21         "Name": "李佳",22         "Sex": "女",23         "Score": 98.824     },25     {26         "ID": 5,27         "Name": "张仁德",28         "Sex": "男",29         "Score": 93.630     }31 ]32 33 print("编号", "\t", "姓名", "\t\t", "性别", "\t\t", "成绩")34 print("-" * 38)35 36 for data in Data:37     Id = data["ID"]38     name = data["Name"]39     sex = data["Sex"]40     score = data["Score"]41     print(Id, "\t\t", name, "\t\t", sex, "\t\t", score)

    输出结果:

    "C:\Program Files\Python39\python.exe" "E:/课件/python/作业10/3json数据格式输出/3 JsonData.py" 编号      姓名          性别          成绩--------------------------------------1          张永华          男          92.72          Test          女          91.33          DingY          男          95.64          李佳          女          98.85          张仁德          男          93.6进程已结束,退出代码0

    data.json文件内容如下

    [{        "ID": 1,        "Name": "张永华",        "Sex": "男",        "Score": 92.7    },    {        "ID": 2,        "Name": "Test",        "Sex": "女",        "Score": 91.3    },    {        "ID": 3,        "Name": "DingY",        "Sex": "男",        "Score": 95.6    },    {        "ID": 4,        "Name": "李佳",        "Sex": "女",        "Score": 98.8    },    {        "ID": 5,        "Name": "张仁德",        "Sex": "男",        "Score": 93.6    }]
  4. 编码将文件student.json中数据导入到文件“student.xls”中。
    1 import xlwt 2 read = open("student.json", "r", encoding="utf-8") 3 data_list = eval(read.read()) 4 work = xlwt.Workbook() 5 sheet = work.add_sheet("Sheet1", cell_overwrite_ok=True) 6 for data in data_list.items(): 7     row = data[0] 8     write_data = data[1] 9     print(write_data)10     sheet.write(int(row)-1, 0, row)11     sheet.write(int(row)-1, 1, write_data[0])12     sheet.write(int(row)-1, 2, write_data[1])13     sheet.write(int(row)-1, 3, write_data[2])14     sheet.write(int(row)-1, 4, write_data[2])15 work.save("student.xls")

输出结果:

"C:\Program Files\Python39\python.exe" "E:/课件/python/作业10/4json数据转xls/student.json to xls.py" ["张三", 93, 97, 99]["李四", 89, 96, 86]["王五", 87, 99, 88]
{ "1": ["张三", 93, 97, 99],     "2": ["李四", 89, 96, 86],    "3": ["王五", 87, 99, 88]  }

关键词: 频率最高 统计结果 文件操作