我想找到一个特定长度的字符串 - 例如 7 个字符。该字符串只能包含大写字母和数字。我有想法:逐行读取文件...
我不确定这里的最佳实践 - 在一个 block 中读取整个文件还是使用循环逐行读取文件?必须使用循环逐行读取文件吗?
# read lines in text file
filetoread=open("mytextfile.txt")
for lines in filetoread # right ?
#just an example of a given string of text (not from the file)
characters = "D123456"
for x in characters:
if x == "D":
print ("found letter", x)
但在我的场景中,我不知道 7 个字符长度的字符串中会出现哪些字符,因此我显然无法搜索“D”。
所以我有想法需要读取文件,检查长度为 7 的字符串(我不确定如何处理文件中的内容,如下所示:
第 1 行:我的路径 =“7 个字符”(因此基本上找到符合 7 个字符且包含大写和数字的子字符串
我不知道,这很简单,但我不认为我理解其背后的基本逻辑。
最佳答案
在 super 巨大的文件中,逐行读取是一个选项。但对于普通文件,一次性读取整个文件会更容易。
我的代码是为普通字符编写的,因此没有特殊的 Ë 和 Ô 类型的字母。
import re
with open("somefile.txt") as file:
data = file.read()
result = re.findall(r'\b[A-Z0-9]{7}\b', data)
print(result)
正则表达式解释:
r'\b[A-Z0-9]{7}\b'
\b = beginning or end of a word
[A-Z] letter range: any letter from capital A to capital Z
[0-9] number range: any number from 0 to 9
{7} length of 7 chars of what is specified in front of it [A-Z0-9]
\b beginning or end of word
关于Python - 在特定长度的文件中查找字符串,并且该字符串必须是大写字母和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62401297/