简体   繁体   English

Python从逗号分隔值中动态选择值

[英]Python dynamically select values from comma separated values

Suppose I have the following strings: 假设我有以下字符串:

University of example1
Assistent professor, hello, University of example2
Hello, University of example3

How can I retrieve only the values that contain "University" so that the output will be as follows? 如何只检索包含“大学”的值,以便输出如下?

University of example1
University of example2
University of example3

Take each String, split it by comma, and then check each slice for "University". 取每个String,用逗号分隔,然后检查每个切片的“大学”。

data = """University of example1
Assistent professor, hello, University of example2
Hello, University of example3"""

data = data.replace("\n",",")   #All one line, split with commas
slices = data.split(",")        #Get each slice
for slice in slices:            #Go through each slice
    if "University" in slice:   #check for magic word
        print slice.strip()     #print out what matches, remove trailing and leading white space

You can turn your string into an array with split and splitlines then use filter or a list comprehension to filter out the ones you don't need. 您可以将字符串转换为包含拆分拆分线的数组,然后使用过滤器或列表推导来过滤掉您不需要的数组。

Something like the below should work: 像下面这样的东西应该工作:

# This will probably come from your file IRL
# We want a list of strings that we can split later and parse
plaintext = """University of example1
Assistent professor, hello, University of example2
Hello, University of example3"""
lines = plaintext.splitlines()


# Define a function to pass into filter
# You'll want to change this to taste, maybe use a regexp depending on requirements
def is_uni(text):

    # Strip out any leading spaces
    return text.lstrip().startswith("Uni")

for line in lines:
    for uni in filter(is_uni,line.split(',')):
        print uni
data_string = "University of example1
Assistent professor, hello, University of example2
Hello, University of example3"
valid_strings = []
strings = data_string.split(",")
for string in strings:
    if "University" in string:
        valid_strings.append(string)

Use valid_strings as you will. 尽可能使用valid_strings

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM