![](/img/trans.png)
[英]how can i search a text file of list of words from user input and print the line which contains these words?
[英]Python: How can I search a text file for a string input by the user that contains an integer?
这是我正在搜索的文本文件上的内容的一个示例:
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
没有理由在if..else
长列表中列出所有单个数字。 您可以使用正则表达式检查行是否以任何数字开头。 如果匹配,请检查它是否与您要查找的数字匹配,如果不匹配,请跳过以下几行,直到到达空白行分隔符。
有了要查找的数据后,就可以再次使用正则表达式查找=
,或者简单地使用.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')
干得好:
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
您可以对所有值应用相同的代码,只需在“ =”之前更改标题。
从文本获取整行,然后仅使用此代码获取“ =”之后的值以输出结果。
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进行操作,它们将仅返回'='之后的值。
尽管我建议不要一般性地搜索整数,但是如果整数也位于捆绑软件或Android版本中怎么办?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.