这是我正在搜索的文本文件的示例:
15 - Project `enter code here`Name
APP_IDENTIFIER=ie.example.example
DISPLAY_NAME=Mobile Banking
BUNDLE_VERSION=1.1.1
HEADER_COLOR=#72453h
ANDROID_VERSION_CODE=3
20 - Project Name
APP_IDENTIFIER=ie.exampleTwo.exampleTwp
DISPLAY_NAME=More Mobile Banking
BUNDLE_VERSION=1.2.3
HEADER_COLOR=#23456g
ANDROID_VERSION_CODE=6
例如,如果用户键入15,我希望python复制以下信息:
ie.example.example
Mobile Banking
1.1.1
#72453h
3
因为我需要将其复制到另一个文本文件中。
我让用户输入一个项目编号(在这个例子中项目编号是15& 20)然后我需要程序来复制项目的app_identifier,display_name,bundle_version和android_version与该编号有关用户输入。
如何让python在文本文件中搜索用户输入的数字,并仅从该特定项目正下方的行中获取所需信息?
我有一个完整的程序,但这只是它的一部分。 我还没有任何代码可以查找和复制我需要的具体信息。 这是我必须搜索项目ID的代码
while True:
CUID = int(input("\nPlease choose an option:\n"))
if (CUID) == 0:
print ("Project one")
break
elif (CUID) == 15:
print ("Project two")
break
elif (CUID) == 89:
print ("Project three")
break
else:
print ("Incorrect input")
Conor的解决方案:
projectFile = open("C:/mobileBuildSettings.txt" , "r")
for line in projectFile:
CUID = str(CUID)
if CUID + " - " in line:
appIdentifier = next(projectFile).split("=")[1]
displayName = next(projectFile).split("=")[1]
bundleVersion = next(projectFile).split("=")[1]
next(projectFile)
androidVersionCode = next(projectFile).split("=")[1]
print (appIdentifier, displayName, bundleVersion, androidVersionCode)
break
答案 0 :(得分:1)
没有理由在长if..else
列表中列出所有个别号码。您可以使用regular expression检查一行是否以任何数字开头。如果是,请检查它是否与您要查找的号码匹配,如果不匹配,请跳过以下行,直至到达空行分隔符。
只要您拥有所需的数据,就可以再次使用正则表达式找到=
,或者只使用.find
:
import re
numberToLookFor = '18'
with open("project.txt") as file:
while True:
line = file.readline()
if not line:
break
line = line.rstrip('\r\n')
if re.match('^'+numberToLookFor+r'\b', line):
while line and line != '':
if line.find('='):
print line[line.find('=')+1:]
line = file.readline().rstrip('\r\n')
else:
while line and line != '':
line = file.readline().rstrip('\r\n')
答案 1 :(得分:1)
你走了:
while True:
CUID = int(input("\nPlease choose an option:\n"))
if (CUID) == 0:
appid = value.split("APP_IDENTIFIER=")[1] # get the value after "APP_IDENTIFIER="
print appid
output >>> ie.example.example
您可以对所有值应用相同的代码,只需在“=”之前更改标题即可。
从文本中获取整行,然后仅使用此代码输出结果输出“=”后的值。
答案 2 :(得分:1)
projectfile = open("projects", "r")
for line in projectfile:
if CUID in line:
appIdentifier = next(projectfile).split("=")[1]
displayName = next(projectfile).split("=")[1]
bundleVersion = next(projectfile).split("=")[1]
next(projectfile)
androidVersionCode = next(projectfile).split("=")[1]
# Do whatever with the 4 values here, call function etc.
break
然后使用appIdentifier,displayName,bundleVersion& androidVersionCode你会做什么,他们只返回'='之后的值。
虽然我建议不要一般地搜索一个整数,如果整数也在bundle或android版本中怎么办?