🐍你的文章代码超过70%了吗|8月更文挑战

前言

今天是8月份更文挑战活动的第一天,这次的活动比此前第一期更文挑战降低了参与门槛,最低只要更文7天!但会发现这期的活动比上期新增了一些文章要求事项,其中就有一项 代码文字比不得超过70% 的要求,我们怎么才能知道我们的文章中代码的占比率是多少呢?

开始主题

我们先创建一个index.md文件,作为我们本文中的测试的文章。

# index.md
今天是2021年8月1号,也是更文挑战的第一天
复制代码

2.png

在根目录下创建一个CheckArticle.py文件,我们把index.md里的内容读取出来看看是否能正常获取到。

# 获取md文件中的内容
with open('index.md', 'r', encoding='UTF-8') as f:
    content = f.read()
    print(content) 
    # 今天是2021年8月1号,也是更文挑战的第一天
复制代码

3.png

创建一个CheckArticle类,它将是用来检测我们的文章的一个类。

class CheckArticle:
    def __init__(self, content):
        self.content = content
复制代码

这个类需要传入一个content参数(markdown文档内容),在__init__中,我们将content参数挂在实例的content属性上。

匹配内容

当我们拿到文档内容之后,接下来就要开始匹配文档中的代码和代码块,看看它们在文档中占据了多少内容。

匹配代码

markdown文档中代码是由两个反引号(`` `)组成的,例如:

`hello world`
复制代码

以上源代码在markdown中的显示效果是这样子是hello world,我们称之为markdown代码

我们写下匹配代码的正则表达式,来匹配我们文章中的“代码”。

`(.*?)` # 匹配代码
复制代码

4.png

在类的__init__方法中把匹配代码的表达式挂载到实例中。

def __init__(self, content):
    self.content = content
    # 匹配代码正则
    self.short_code = r'`(.*?)`'
复制代码

CheckArticle类中创建一个match_short_code方法,用来匹配我们文档内容中的”代码“。

class CheckArticle:
	# 忽略一些代码
    def match_code(self):
        short_code_result = re.findall(self.short_code, self.content)
        print(short_code_result)
复制代码

现在我们将代码跑起来匹配的是空的,因为我们文档中没有符合正则表达式的要求。

我们需要在index.md文件中新增几个代码和代码块,以便于我们接下来的测试。

# index.md
今天是`2021``8``1`号,也是更文挑战的第一天

```javascript
console.log('javascript')
```

```
一段未知的代码
```

复制代码

6.png

运行下代码看看“代码”能不能匹配到。

with open('index.md', 'r', encoding='UTF-8') as f:
    content = f.read()
    print(CheckArticle(content).match_short_code())
复制代码

什么情况?为什么会有空的字符串呢?

7.png

nt.jpg

我们把表达式和markdown文档中的内容贴到regexr中查看一下。

8.png

原来是下面代码块引起的问题,我们在match_short_code函数中做一下处理,用filter函数把空的字符串给去除掉,再通过for语句获得所有项的长度的和。

我们再运行一遍试试 ~ ~

def match_short_code(self):
    short_code_result = re.findall(self.short_code, self.content)
    short_code_result = filter(None, short_code_result)
    sum = 0
    for item in short_code_result:
        sum += len(item)
    return sum
复制代码

9.png

NICE!现在返回6的意思是当前文档代码占用的长度6,和index.md文档中的长度一致。

匹配代码块

在markdown文档中,还可以使用```来包裹代码,这种方式通常用于包裹多行代码,例如

```
	print(’hello world‘)
	print(‘hello world’)
```
复制代码

我们来写下匹配代码块的正则表达式。

```([\s\S]*?)``` # 匹配代码块
复制代码

5.png

同上,将这个匹配代码块的表达式挂载到实例中。

def __init__(self, content):
    # 忽略一些代码
    # 匹配代码块正则
    self.long_code = r'```([\s\S]*?)```'
复制代码

CheckArticle类中创建一个match_long_code方法,用来匹配我们文档内容中的```代码块```

def match_long_code(self):
    long_code_result = re.findall(self.long_code, self.content)
    sum = 0
    for item in long_code_result:
        # 去除 \n  影响长度
        sum += len(item.replace("\n", ""))
    return sum
复制代码

运行一下

10.png

没问题,返回代码块的长度与index.md中的代码块长度一致

我们把代码和代码块的长度存储下

def __init__(self, content):
    # 忽略一些代码
    # 代码长度
    self.short_code_len = self.match_short_code()
    # 代码块长度
    self.long_code_len = self.match_long_code()
复制代码

计算代码占比

创建一个get_code_percent方法,该方法需要传入 代码 / 代码块 的长度

def get_code_percent(self, num):
    return str(round((num / self.content_len) * 100, 2)) + '%'
复制代码

__init__方法中,新增两行代码

def __init__(self, content):
    # 计算代码占比
    self.short_percent = self.get_code_percent(self.short_code_len)
    self.long_percent = self.get_code_percent(self.long_code_len)
复制代码
# 获取md文件中的内容
with open('index.md', 'r', encoding='UTF-8') as f:
    content = f.read()
    index_md = CheckArticle(content)
    print('代码占比率', index_md.short_percent)  # 代码占比率 6.52%
    print('代码块占比率', index_md.long_percent)  # 代码块占比率 45.65%
复制代码

优化

目标:在运行脚本的时候输入文件路径,直接输出代码的占比率

清空CheckArticle.py文件中,除了CheckArticle类的代码之外的代码

新建index.py文件

# index.py
import os, sys
from CheckArticle import CheckArticle

# 获取文件路径
file_path = input("输入你需要检测的文章文件路径(支持相对路径):\n")
if not os.path.exists(file_path):
    print('文件不存在,请检查路径是否正确')
    sys.exit()

# 获取md文件中的内容
try:
    with open(file_path, 'r', encoding='UTF-8') as f:
        content = f.read()
        index_md = CheckArticle(content)
        print('代码占比率', index_md.short_percent)  # 代码占比率 6.52%
        print('代码块占比率', index_md.long_percent)  # 代码块占比率 45.65%
except:
    print('读取出错了')
复制代码

11.png

我们看看现在你正在阅读的这一篇文章的代码 / 代码块占比:

输入你需要检测的文章文件路径(支持相对路径):
./20210801.md
代码占比率 7.5%
代码块占比率 30.96%
复制代码

最后

祝小伙伴们,在八月份的更文挑战中打怪升级拿到自己心仪的奖品 😁😁

如果你觉得还有什么可以优化的点子 可以在评论区提出 📃 📃

另外正在写个在线版