2017-04-03 56 views
1

我有一個56種不同魚種的列表(或者如果我選擇,可以是集合或元組)。我想通過CSV文件「掃描」來識別任何魚類的發生。Python - 識別字符串中的值

我想:

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' 
     ) 
+0

'stocks'是一個元組。您正在查找字符串中的元組對象。相反,你需要一個單獨的'for'循環遍歷整個元組中的每個字符串。 – roganjosh

+0

你是否考慮過把股票變成一套 - 也就是'sstocks = set(股票)' – user1245262

回答

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) 
+0

所以我認爲它有效,但只是一個快速跟進問題:它不打印任何東西,我認爲是因爲'股票'元組是總之,有沒有辦法忽略大/小寫?我知道存在RegEx – theprowler

+1

是的,你可以更新條件:'stock(stock.lower()in line.lower()。strip()for stock in stocks)' – Elisha

+0

它說:'AttributeError:'builtin_function_or_method'對象沒有屬性'strip''這是否意味着'strip()'不能在文件上工作? – theprowler

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): 
0

如果左操作數也是字符串類型,則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)