我有一个带有大量随机单词和数字的长文本行,我希望将一个变量分配给该行中唯一的3位数字.
数字会改变每一行,但总是只有3位数.如何在linepython中搜索唯一的3位数字?可能有3个字母的单词,所以它必须只是数字.
09824747 18 n 02 archer 0 bowman 0 003 @ 09640897 n 0000
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我想要变量数字= 003
您可以使用正则表达式.或者查找一个数字,然后手动检查接下来的两个字符.
我会使用正则表达式:
import re
threedig = re.compile(r'\b(\d{3})\b') # Regular expression matching three digits.
Run Code Online (Sandbox Code Playgroud)
的\b意思是"单词边界",并(\d{3})表示"三位数",括号使它成为一个"组",所以匹配的文本都可以找到.
然后搜索使用:
mo = threedig.search("09824747 18 n 02 archer 0 bowman 0 003 @ 09640897 n 0000")
if mo:
print mo.group(1)
Run Code Online (Sandbox Code Playgroud)
以上打印333.
带有\b单词边界的正则表达式可以解决这个问题:
re.findall(r'\b\d{3}\b', inputtext)
Run Code Online (Sandbox Code Playgroud)
返回所有3位数字的列表.
演示:
>>> import re
>>> inputtext = '09824747 18 n 02 archer 0 bowman 0 003 @ 09640897 n 0000'
>>> re.findall(r'\b\d{3}\b', inputtext)
['003']
>>> inputtext = 'exact: 444, short: 12, long: 1234, at the end of the line: 456'
>>> re.findall(r'\b\d{3}\b', inputtext)
['444', '456']
Run Code Online (Sandbox Code Playgroud)