python - 我有一个 txt 文件,想打印特定的单词
问题描述
这是我的文本文件:
10.10.10.10 POST /include/jquery.js HTTP/1.1 233
192.10.10.12 POST /include/jquery.js HTTP/1.1 232
10.10.10.12 POST /node/jquery.jshowoff2.js HTTP/1.1 23e
171.1.1.15 POST /include/jquery.min.js HTTP/1.1 121
10.10.10.10 POST /text/jquery.sho.min.js HTTP/1.1 233
我只想打印包含的文件名.js
。例如,对于我想要打印出来的第一行:
jquery.js
这就是我现在拥有的,但它正在打印完整的行
import re
import sys
linenum = 0
substr = '.js'
with open ('access_log.txt', 'rt') as myfile:
for line in myfile:
linenum += 1
if line.find(substr) != -1:
print(line, end=' ')
输出:
10.10.10.10 POST /include/jquery.js HTTP/1.1 233
192.10.10.12 POST /include/jquery.js HTTP/1.1 232
10.10.10.12 POST /node/jquery.jshowoff2.js HTTP/1.1 23e
171.1.1.15 POST /include/jquery.min.js HTTP/1.1 121
10.10.10.10 POST /text/jquery.sho.min.js HTTP/1.1 233
解决方案
以下是如何使用该rfind()
方法查找'/'
字符串中最后出现的索引(如果有的话):
import re
with open('access_log.txt', 'r') as myfile:
for line in myfile:
st = line.split()
print([a[a.rfind('/')+1:] for a in st if a.endswith('.js')])
输出:
['jquery.js']
['jquery.js']
['jquery.jshowoff2.js']
['jquery.min.js']
['jquery.sho.min.js']
推荐阅读
- html - 如何管理月份和年份的下拉菜单?
- apache-spark - 使用 Python 中的 Spark Structured Sreaming 从 Kafka 读取数据并打印到控制台
- javascript - 如何按子文档分组并获取 value 字段的唯一值?
- javascript - 不和谐.js | 我如何做到这一点,使其每 2 或 3 个单词输入一个新行?
- flutter - 将 Sqlite 表导出到文件并在 Flutter 中重新导入
- bitcoin - 我们可以在不知道私钥的情况下进行加密货币交易吗
- list - applescript - 在定义的列表中使用条件系统
- c# - C#,WPF,加载默认视图
- javascript - 如何在javascript中缩短这个条件?
- javascript - Javascript字符串一次替换一个并添加到数组