【问题标题】:Python - Find string in file of certain length and the string must be uppercase and number onlyPython - 在一定长度的文件中查找字符串,字符串必须是大写和数字
【发布时间】:2020-10-05 15:17:03
【问题描述】:

我想找到一个特定长度的字符串 - 例如 7 个字符。字符串只能包含大写字母和数字。我有想法:逐行读取文件...

我不确定这里的最佳做法是在一个块中读取整个文件还是使用循环逐行读取文件?是否必须使用循环逐行读取文件?

# 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 行:我的路径 = "7characters"(所以基本上可以找到包含大写和数字的 7 个字符的子字符串

我不知道,这很简单,但我不认为我理解它背后的基本逻辑。

【问题讨论】:

  • 你可以有你的条件,比如先导入这个模块:import string,然后有一个条件:if(x in string.ascii_uppercase or x in string.digits):
  • 这些字母和数字仅是 ASCII 字母吗?说A-Z 加上0-9?
  • 这个链接讨论了一个可以提供帮助的外部模块:stackoverflow.com/questions/36187349/…

标签: python string alphanumeric


【解决方案1】:

unicode 规范中有很多大写字母和数字。这个例子将规范化文件的每一行,然后检查每个字符的字符类。如果 unicode 表示它的大写字母,它会计数。 (我假设 emoji 不会有大写版本...)。

import unicodedata

def string_finder(filename, length=7):
    with open(filnname) as fp:
        return_chars = []
        for line in fp:
            line = unicodedata.normalize(line.strip())
            for c in line:
                category = unicodedata(c)
                if "LU" in category or "N" in category:
                    return_chars.append(c)
                    if len(return_chars) == length:
                        return "".join(return_chars)
    return None

【讨论】:

    【解决方案2】:

    逐行阅读将是超大文件中的一个选项。但是对于普通文件,一次读取整个文件会更容易。

    我的代码是为普通字符编写的,所以没有特殊的 Ë 和 Ô 类字母。

    import re
    
    with open("somefile.txt") as file:
       data = file.read()
       result = re.findall(r'\b[A-Z0-9]{7}\b', data)
       print(result)
    

    正则表达式解释:

    \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
    

    【讨论】:

      【解决方案3】:

      一般来说,正则表达式 (regex) 是在文件中搜索满足特定条件的字符串的最简洁和最快的方法。我建议使用RegEXR 工具为您可能拥有的每个特定用例开发正则表达式。对于您的情况(在文件中查找 7 个连续的大写或数字字符),我会这样做:

      import re
      
      # with open("examplefile.txt") as f:
      #     text = f.read()
      
      # This is just an example, since I don't have your text file
      text = """
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
      Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
      when an unknown printer took a G4LL3YS of type and scrambled it to make a type specimen book. 
      It has survived not only five centuries, but also the leap into ELEC7R0NIC typesetting, remaining essentially unchanged.
      It was popularised in the 19601970s with the release of LETRASET sheets containing Lorem Ipsum passages, 
      and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
      """
      # Searches fo the pattern in the sample text
      found_patterns = re.findall(r'([A-Z\d]{7})', text)
      # Could also use below, if you only want the first match
      # found_patterns = re.search(r'([A-Z\d]{7})', text).group()
      print(found_patterns)
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-13
        • 2012-06-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多