Python - 识别字符串中的值

时间:2017-04-03 15:15:06

标签: python string

我有56种不同鱼类的清单(或者我选择的一套或一组)。我想通过CSV文件“扫描”以识别任何鱼类的任何发生。

我试过了:

with open(file_path) as f:
    for line in f:
        if (stocks in line):
            fish, remainder = line.split('\t')
            print("fish:", fish)
            print("remainder:", remainder)

但由于以下原因失败:

TypeError: 'in <string>' requires string as left operand, not tuple

所以我正在寻找一种成功的方法。

可能发生的列表:

stocks = (
        'GB COD EAST',
        'GBE COD',
        'GB COD WEST',
        'GBW COD',
        'GOM COD',
        'GB HADDOCK EAST',
        'GBE HADD',
        'GB HADDOCK WEST',
        'GBW HADD',
        'GOM HADDOCK',
        'GOM HADD',
        'GOM HAD',
        'GOM HADOCK',
        'PLAICE',
        'DABS',
        'POLLOCK',
        'POLL',
        'REDFISH',
        'REDS',
        'RED',
        'WHITE HAKE' ,
        'WHITEHAKE',
        'WHAKE',
        'WHAK',
        'GB WINTER FLOUNDER',
        'GB BB',
        'GB WINTER',
        'GB BLACK BACKS',
        'GB BLACKBACKS',
        'GOM WINTER FLOUNDER',
        'GOM BLACKBACKS',
        'GOM BB',
        'GOM WINTER',
        'SNE WINTER FLOUNDER',
        'SNE WINTER',
        'SNE/MA WINTER FLOUNDER',
        'SNE BLACKBACK',
        'SNE BLACKBACKS',
        'SNE BB',
        'WITCH FLOUNDER',
        'WITCH',
        'WHICH',
        'WHITCH',
        'GREYSOLE',
        'GREY SOLE',
        'CC/GOM YELLOWTAIL FLOUNDER',
        'GOM YELLOWTAIL',
        'GOM YELLOW TAIL',
        'GOM YT',
        'GB YELLOWTAIL FLOUNDER',
        'GB YELLOWTAIL',
        'GB YT',
        'SNE/MA YELLOWTAIL FLOUNDER',
        'SNE YT',
        'SNE YELLOWTAIL',
        'SNE YELLOW TAIL',
        'SCALLOP IFQ'
        )

3 个答案:

答案 0 :(得分:1)

with open(file_path) as f:
    for line in f:
        if any(stock.lower() in line.lower().strip() for stock in stocks):
            fish, remainder = line.split('\t')
            print("fish:", fish)
            print("remainder:", remainder)

答案 1 :(得分:1)

stocks是一个元组,你无法检查元组是否在字符串中

>>> ("a", "b") in "ab"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not tuple

您可以改为使用built-in any() function

if any(stock in line for stock in stocks):

答案 2 :(得分:0)

如果左操作数也是string类型,Python只允许你使用带有类型字符串的右操作数的in运算符。

if (stocks in line):

股票是一个元组,而行是字符串。您可以使用以下方法,假设您需要所有匹配项,包括重复项:

with open(file_path) as f: for line in f: matches = [x for x in stocks if x in line] print(matches)