我正在从 10 行的文本中找到一行。
desc = re.findall(r'@description (.*)', comment.strip())
发生的是它返回 @description 但它也有 9 个空列表。
print(desc)
返回:
[]
[]
[]
[]
[]
[]
[]
[]
['the desc is here']
[]
那么如何摆脱那些空的 [] 并使 desc=['the desc is here']?
更新
我试过列表过滤器,结果还是一样
评论包含:
/**
* @param string username required the username of the registering user
* @param string password required
* @param string first_name required
* @param string last_name required
* @param string email required
* @package authentication
* @info user registration
* @description register a new user into the groupjump platform
*/
更新
comment是一个完整的字符串,所以我把它拆分成这样,这样我就可以逐行阅读
comments = route['comment']
comments = list(filter(None, comments.split('\n')))
实际代码
#!/usr/bin/env python3
import re
routes = []
description = ''
with open('troutes.php', 'r') as f:
current_comment = ''
in_comment = False
for line in f:
line = line.lstrip()
if line.startswith('/**'):
in_comment = True
if in_comment:
current_comment += line
if line.startswith('*/'):
in_comment = False
if line.startswith('Route::'):
matches = re.search(r"Route::([A-Z]+)\('(.*)', '(.*)'\);", line)
groups = matches.groups()
routes.append({
'comment': current_comment,
'method': groups[0],
'path': groups[1],
'handler': groups[2],
});
current_comment = '' # reset the comment
for route in routes:
# get comments
comments = route['comment']
comments = list(filter(None, comments.split('\n')))
for comment in comments:
params = re.findall(r'@param (.*)', comment.strip())
object = re.findall(r'@package (.*)', comment.strip())
info = re.findall(r'@info (.*)', comment.strip())
desc = re.search(r'@description (.*)', comment.strip())
print(comment[15:])
正在读取的数据:
<?php
/**
* @param string username required the username of the registering user
* @param string password required
* @param string first_name required
* @param string last_name required
* @param string email required
* @package authentication
* @info user registration
* @description register a new user into the groupjump platform
*/
Route::POST('v3/register', 'UserController@Register');
/**
* @param string username required the username of the registering user
* @param string password required
*/
Route::GET('v3/login', 'UserController@login');
请您参考如下方法:
单个列表的条件是:
if desc:
print(desc)
它是以下内容的简写版本:
if len(desc) > 0:
print(desc)
对于列表的列表,它是:
desc = [d for d in desc if d]
要仅获取字符串,请执行以下操作:
if desc:
print(desc[0])
