V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
jeblur
V2EX  ›  Python

想要读取一个文件并筛选特定的文件名该怎么做呢

  •  
  •   jeblur · Aug 26, 2020 · 1612 views
    This topic created in 2070 days ago, the information mentioned may be changed or developed.

    Very Very New to Python... 我的想法是先 with open 打开文件,然后读每行的内容,并用正则表达式筛选特定的内容。

    但查了很多代码好像都没能做成

    import re
    import os
    import sys
    
    stringToMatch = '[^/]*\.js'
    matchedLine = ''
    
    with open('access_log.txt') as f:
            for line in f:
                    if stringToMatch in line:
                            print line
    

    上面是其中一个。。 运行后完全没有输出[一脸懵]

    3 replies    2020-08-26 15:43:57 +08:00
    imn1
        1
    imn1  
       Aug 26, 2020
    stringToMatch = r'[^/]+\.js'
    ...
    if re.search(stringToMatch, line):
    ...
    jeblur
        2
    jeblur  
    OP
       Aug 26, 2020
    @imn1 太感谢了!可以输出 line 了,还想问下如果要匹配特定的值,比如代码中的*.js 文件,要换掉 search 这个方法吗。关于这个正则表达式我能理解的是匹配到第一个 /开始然后以.js 结尾,最后我需要加$结束吗。

    抱歉问了这么多问题:>
    imn1
        3
    imn1  
       Aug 26, 2020
    你理解错了
    这个正则是 一个或多个不是“/”的字符后面紧接.js ,在一行里面的任意位置,没有方括号的^才是行首
    如果你确定匹配结尾是.js 才用$,如果在行中间就不需要( line 最后应该是个换行符,不过你可以测试一下能否匹配)
    re 里面有很多匹配的方法,只是这个 search 用于“是否匹配”比较简单,根据需要你可以用其他的

    你需要学习正则,以及 re 的方法
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1061 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 18:46 · PVG 02:46 · LAX 11:46 · JFK 14:46
    ♥ Do have faith in what you're doing.