[英]Python: if string starts with a string from a list
我正在讀取文件,並且每行都有一個標記,然后是一個冒號,然后是我想要的信息。 一個樣本文件看起來像
Package: com.something.something
Section: Utilities
Name: Something
等等,(如果您想知道的話,這是一個apt軟件包索引)
所以我想遍歷每一行,看看該行是否以列表中的元素開頭。 我在想類似
PkgInfo={}
Tags=['Package', 'Section', 'Name']
for line in reader.readlines()
if line.startswith(element in Tags):
PkgInfo[element]=line.split(': ')[1]
該代碼不起作用,但是希望您理解我正在嘗試做的事情。 我將如何實現這一目標?
邏輯稍有不同的工作解決方案:
PkgInfo={}
Tags=['Package', 'Section', 'Name']
for line in reader.readlines():
entry = line.strip().split(': ', 2)
if len(entry) != 2:
continue
element, value = entry[0], entry[1]
if element in Tags:
PkgInfo[element] = value
print PkgInfo
並注意以下事實:元素上的迭代不僅僅是一個問題。 在“包” Tags
被定義為“包:”, Tags
在環路中引用tags
, split.line
代替line.split()
值不被剝離。
我建議您在:
處分行,然后測試第一部分是否是您的關鍵字之一。 這可以通過使用set
和in
運算符輕松完成:
tags = set(['Package', 'Section', 'Name'])
pkgInfo = {k: v.strip() for k, v in (line.split(':') for line in reader) if k in tags}
或更長的版本:
tags = set(['Package', 'Section', 'Name'])
pkgInfo = {}
for line in reader:
k, v = line.split(':')
if k in tags:
pkgInfo[k] = v.strip()
但是請注意,如果每行中沒有一個冒號,這將失敗。
嘗試這個:
PkgInfo = {}
Tags = ['Package', 'Section', 'Name']
for line in reader.readlines():
for element in Tags:
if line.startswith(element):
PkgInfo[element] = line.split(': ')[1]
break
所有基於split()的解決方案的問題在於,如果冒號出現不止一次,它們可能會中斷。 這不是那么優雅,但更強大:
PkgInfo = {}
Tags = ['Package','Section','Name']
splitter = ': '
splitLen = len(splitter)
for line in reader.readlines():
firstColon = line.find(splitter)
if firstColon > 0:
key = line[:firstColon]
if key in Tags:
pkgInfo[key] = line[firstColon + splitLen:]
您需要遍歷標簽:
PkgInfo={}
Tags=['Package: ', 'Section', 'Name']
for line in reader.readlines():
for tag in Tags:
if line.startswith(tag):
PkgInfo[tag]=line.split(': ')[1]
break
我會嘗試這樣的事情:
PkgInfo={}
#I assume it should be 'Package' not 'Package: '
Tags=['Package', 'Section', 'Name']
for line in reader.readlines()
k, v = line.split(': ')
if k in Tags:
PkgInfo[k] = v
甚至更快更臟的兩種襯里:
#I assume it should be 'Package' not 'Package: '
Tags=['Package', 'Section', 'Name']
PkgInfo = dict(line.split(': ') for line in reader.readlines() if line.split(': ')[0] in Tags)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.