python - 在外部文件中搜索特定单词并将下一个单词存储在 Python 中的变量中
问题描述
我有一个文件,其中包含与此类似的行:
"string" "playbackOptions -min 1 -max 57 -ast 1 -aet 57
现在我想搜索文件并提取“-aet”(在本例中为 57)之后的值并将其存储在变量中。
我在用着
import mmap
with open('file.txt') as f:
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find('-aet') != -1:
print('true')
用于搜索。但不能超越这一点。
解决方案
我建议使用正则表达式来提取值:
import re
# Open the file for reading
with open("file.txt", "r") as f:
# Loop through all the lines:
for line in f:
# Find an exact match
# ".*" skips other options,
# (?P<aet_value>\d+) makes a search group named "aet_value"
# if you need other values from that line just add them here
line_match = re.search(r"\"string\" \"playbackOptions .* -aet (?P<aet_value>\d+)", line)
# No match, search next line
if not line_match:
continue
# We know it's a number so it's safe to convert to int
aet_value = int(line_match.group("aet_value"))
# Do whatever you need
print("Found aet_value: {}".format(aet_value)
推荐阅读
- mysql - 如何根据来自不同表的几个条件mysql计算百分比
- haskell - Haskell 中具有挑战性的列表理解问题
- firebase - 将用户自定义域连接到 Firebase 应用
- c# - 如何在 EF Core 中对导航属性执行子查询?
- javascript - 'Readonly<{ IGoogleMapTrackerProps }> & Readonly<{ chirldren?: ReactNode; 类型上不存在属性 'google' }>'
- python - 使用 Python 需要搜索一个字符串
- visual-studio-code - 在片段“字符串”中创建一个停止
- kotlin - 为什么 BiPredicate.test 方法在 Kotlin 中不可见?
- django - 如何在共享模式和租户模式中正确拥有 contrib.auth
- python - 动态增加 asyncio.Queue 的大小?