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

时间:2015-06-11 20:45:50

标签: python

假设我有以下字符串:

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

如何只检索包含"大学"的值?以便输出如下?

University of example1
University of example2
University of example3

3 个答案:

答案 0 :(得分:1)

取每个String,用逗号分隔,然后检查每个切片是否为“University”。

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

答案 1 :(得分:1)

您可以将字符串转换为包含splitsplitlines的数组,然后使用filter或列表理解来过滤掉您不需要的字符串。

以下内容应该有效:

# 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

答案 2 :(得分:1)

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)

尽可能使用valid_strings