Car*_*son 41 python regex file-io text-mining string-parsing
所以基本上我正在寻找文本文件中两个尖括号内的4位数代码.我知道我需要打开文本文件然后逐行解析,但我不确定在检查"for line in file"之后构建代码的最佳方法.
我想我可以以某种方式拆分它,剥离它或分区,但我也写了一个我使用编译的正则表达式,所以如果它返回一个匹配对象,我不认为我可以使用那些基于字符串的操作.另外我不确定我的正则表达式是否足够贪婪......
我想将所有找到的匹配的实例存储为元组或列表中的字符串.
这是我的正则表达式:
regex = re.compile("(<(\d{4,5})>)?")
Run Code Online (Sandbox Code Playgroud)
考虑到目前为止相当基本的代码,我认为我不需要包含所有代码.
Eli*_*sky 41
import re
pattern = re.compile("<(\d{4,5})>")
for i, line in enumerate(open('test.txt')):
for match in re.finditer(pattern, line):
print 'Found on line %s: %s' % (i+1, match.group())
Run Code Online (Sandbox Code Playgroud)
关于正则表达式的几个注释:
?在末尾和外部(...),但只需要数字本身更新:重要的是要理解正则表达式中的匹配和捕获可能完全不同.我上面的代码段中的正则表达式使用尖括号匹配模式,但我要求仅捕获内部数字,而不使用尖括号.
Jos*_*iah 22
一次性阅读:
import re
textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)
Run Code Online (Sandbox Code Playgroud)
逐行:
import re
textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += reg.findall(line)
textfile.close()
Run Code Online (Sandbox Code Playgroud)
但同样,除非您添加了偏移计数器,否则返回的匹配对除计数之外的任何内容都没有用:
import re
textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += [(reg.findall(line),offset)]
offset += len(line)
textfile.close()
Run Code Online (Sandbox Code Playgroud)
但是,立即读取整个文件仍然更有意义.