【问题标题】:Python - Extract Code from Text using RegexPython - 使用正则表达式从文本中提取代码
【发布时间】:2018-11-09 08:30:33
【问题描述】:

我是一名 Python 初学者,正在寻求有关提取问题的帮助。

我有一堆文本文件,需要提取一个表达式的所有特殊组合(“C”+“正好 9 个数字”)并将它们写入一个包含文本文件文件名的文件。我想捕捉的表达式的每次出现都从新行的开头开始,并以“/n”结尾。

sample_text = """Some random text here 
and here
and here
C123456789
some random text here
C987654321
and here
and here"""

输出应该是什么样子(在输出文件中)

My_desired_output_file = "filename,C123456789,C987654321"

到目前为止我的代码:

min_file_size = 5

def list_textfiles(directory, min_file_size): # Creates a list of all files stored in DIRECTORY ending on '.txt'
    textfiles = []
    for root, dirs, files in os.walk(directory):
        for name in files:
            filename = os.path.join(root, name)
            if os.stat(filename).st_size > min_file_size:
                textfiles.append(filename)

for filename in list_textfiles(temp_directory, min_file_size):         
    string = str(filename)
    text = infile.read()
    regex = ???
    with open(filename, 'w', encoding="utf-8") as outfile:
       outfile.write(regex)

【问题讨论】:

  • 您可以随时使用在线测试工具测试您的正则表达式,例如regex101.com
  • 如果你不介意在每场比赛的前面加上文件名:grep -r -E '^C[0-9]{9}$' --exclude out.txt > out.txt
  • 只需添加-h 即可避免在grep 中打印文件名

标签: python regex text-extraction


【解决方案1】:

你的正则表达式是'^C[0-9]{9}$'

^           start of line
C           exact match
[0-9]       any digit
{9}         9 times
$           end of line

【讨论】:

  • 非常感谢!这个正则表达式会将表达式的每个出现都存储在一个列表中,以便我可以将它写入一个输出文件?
  • 来吧,包括你的代码尝试或谷歌它
【解决方案2】:
import re

regex = re.compile('(^C\d{9})')
matches = []
with open('file.txt', 'r') as file:
    for line in file:
        line = line.strip()
        if regex.match(line):
            matches.append(line)

然后您可以根据需要将此列表写入文件。

【讨论】:

    【解决方案3】:

    怎么样:

    import re
    
    sample_text = """Some random text here 
    and here
    and here
    C123456789
    some random text here
    C987654321
    and here
    and here"""
    
    k = re.findall('(C\d{9})',sample_text)
    
    print(k)
    

    这将返回该模式的所有出现。如果您从文本中产生行并存储您的目标组合。比如:

    更新:

    import glob
    import os
    import re
    
    search = {}
    os.chdir('/FolderWithTxTs')
    for file in glob.glob("*.txt"):
        with open(file,'r') as f:
            data = [re.findall('(C\d{9})',i) for i in f]
            search.update({f.name:data})
    
    print(search)
    

    这将返回一个以文件名作为键的字典和找到的匹配项列表。

    【讨论】:

    • {9,9} 等价于{9}
    • 我建议如下:data = re.findall(r'C\d{9}', f.read())... 或 data = [re.match(r'C\d{9}', i) for i in f]... 如果您只是将出现的事件添加到平面列表中,您也会丢失文件名的信息。
    • 感谢您的 cmets。我会尽快更新代码
    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 2015-01-16
    相关资源
    最近更新 更多