鱼C论坛

 找回密码
 立即注册
查看: 1162|回复: 2

【统计代码行数】如何判断一个字符串是否已经在txt文档里?

[复制链接]
发表于 2019-7-23 15:28:34 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
想实现统计文件夹内总共的代码行数。实现将代码名称与行数这一字典保存成文件时发现没法判断某一字符串是否在文本文件里,应该如何解决呢?
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Jul 23 10:01:46 2019

  4. @author: u
  5. """

  6. import glob
  7. import datetime
  8. import re

  9. nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')#现在
  10. file_name1 = r'Total_code_count.txt'
  11. file_name2 = r'Code_count_details.txt'
  12. files = glob.glob(r'D:\FishC_learning\*.py')
  13. len_dict = {}

  14. total_count = 0
  15. for each_py in files:
  16.      this_count = 0
  17.      with open(each_py,'r', encoding='UTF-8') as py:
  18.             for each_line in py:
  19.                    this_count += 1
  20.             len_dict[each_py] = this_count
  21.      total_count += this_count
  22.      
  23. #print(len_dict.items())
  24. print(total_count)

  25. with open(file_name1,'a+') as f1:
  26.        strings =nowTime + '时刻本文件夹的代码总数为:' + str(total_count) + '\n'
  27.        print(strings)
  28.        f1.writelines(strings)

  29. with open(file_name2,'r+') as f2:
  30.        for each_py in len_dict.keys():
  31.               if each_py not in f2.read():
  32.                      strings2 = str(each_py) + ' 的代码数为:' + str(len_dict[each_py]) + '\n'
  33.                      print(strings2)
  34.                      f2.writelines(strings2)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2019-7-23 15:49:16 | 显示全部楼层
就在最下面的代码段里:
  1. for each_py in len_dict.keys():
  2.               if each_py not in f2.read():
复制代码

这个功能失效了,尝试用find方法也不行。
用正则表达式传出什么/F错误,从来没见过。。。
有毒
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-7-23 17:10:27 | 显示全部楼层
用os模块中的os.listdir()函数可以得到一个路径下所有的文件名称
然后用正则表达式就没问题了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-1-17 03:02

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表