我们可以使用regular expression通过建立一个模式来提取名称:
通常情况下,我们的作者关键字后发现作者的名字,作为注释。有些人宁愿使用__author__
并在:
或::
或=
或==
之后写上名称。这取决于你通常观察到什么。我们鼓励在github上查看人们在评论中如何使用作者。
作者的名字通常在此之后出现,有些人使用昵称,所以它始终不是alphabitic。
pattern= r'.*author*.[^:=]*[:=]*(.[^\n]+)'
在正则表达式中。意味着任何charachter,并且+意味着一个或更多,除了charachter之外意思。除了新行之外,你想在文本中“匹配”一个或多个字符(有些人在写第一个或最后一个名字时也可能使用空格)。括号表示捕获单词中找到的内容,该单词应该在接受任何charchter的特定文本“作者”之前找到,以及之后的任何特许文件,除了'= /:',':/ ='之后用于识别另一部分。
除了你做什么来打开文件,验证格式。让我们考虑这个简单的例子来说明如何使用正则表达式来提取作者姓名的想法。
#simple case
data1= """
author='helloWorld'
def hello()
print "hello world"
"""
# case with two ::
data2= """
__author__::'someone'
def hello()
print "hello world"
"""
#case where we have numerical/alphabetic
data3= """
__author__='someone201119'
def hello()
print "hello world"
"""
#Case where no author in code
data4= """
def hello()
print "hello world"
"""
for data in [data1,data2,data3,data4]:
m= re.match(r'.*author*.[^:=]*[:=]*(.[^\n]+)',data,re.DOTALL)
if m:
author= m.group(1)
else:
author='unkown'
print "author is this case is:", author
输出:
author is this case is: 'helloWorld'
author is this case is: 'someone'
author is this case is: 'someone201119'
author is this case is: unkown
UPDATE
你过所有的代码是这样:
import os
import re
folderpath = 'D:/Workspace'
typeOfFile = [".c", ".C", ".cpp", ".CPP"]
for dirname, dirnames, filenames in os.walk(folderpath):
for filename in filenames:
if filename.endswith(tuple(typeOfFile)):
data= open(os.path.join(dirname, filename), "r").readlines():
m= re.match(r'.*author*.[^:=]*[:=]*(.[^\n]+)',data,re.DOTALL)
if m:
author= m.group(1)
else:
author='unkown'
print "author is this case is:", author, "in file", filename
其实我需要从文件的作者。我正在做脚本,并把它放到excel文件中。我的老板给了我需要找到作者的项目。每个文件夹中的每一个都需要检查。它有近2000个c和C++文件。还有一些没有作者。所以,当我在Excel文件上打印它。有些文件缺少作者,因为所有作者都在上面堆叠。所以我需要其他功能来打印未知。谢谢你的回复.. – 2014-11-09 07:24:21
看来你错过了这个答案背后的观点。 (UPDATE)部分中的脚本执行您提到的内容。答案解释了如何从不同的案例中提取作者,而没有强调如何打开和阅读不同的文件(假设你知道,因为你已经完美地写了它)。再次检查UPDATE,你的代码看起来就像那样。 – 2014-11-09 14:50:33
为什么我的python库错误?像这样'return_compile(pattern,flags).match(string) TypeError:expected string or buffer' – 2014-11-11 15:07:08