gpt4 book ai didi

Python IO 不可哈希列表正则表达式

转载 作者:行者123 更新时间:2023-11-30 23:29:03 25 4
gpt4 key购买 nike

我有一个从 txt 文件加载的列表,并运行一些代码来匹配数据。但我得到 TypeError: Unhashable list 我查看了 Stack 上的几个答案,但找不到我将列表传递到循环中的位置。我猜它与 df 有关,因为当我不使用加载的数据时它会起作用。

import pandas as pd
import re

#Capture tester
df = pd.read_csv('patterntest.txt', header=None, dtype=str)
df.columns = ['names']
df['status']=''

patterns=['(?i)(C|F|L)at', 'Dog']


for i in xrange(len(patterns)):
df.loc[df.names.str.match(patterns[i]),'status'] = 'CAPTURED'

print df

我也没有看到我将列表传递到 for 循环中的位置。

“patterntest.txt”文件中的所有内容只是一些文本,例如:

dog
cat
mouse
frog
fox
canis sp

这是我的输入

import pandas as pd
import re

#Capture tester
df = pd.read_csv('patterntest.txt', header=None, dtype=str)
df.columns = ['names']
df['status']=''

patterns=['(?i)(C|H|L)at', 'Dog']




##
##for i in xrange(len(patterns)):
## df.loc[df.names.str.match(patterns[i]),'status'] = 'CAPTURED'

print df.names.str.match(patterns[0])
print df.names.str.match(patterns[1])

输出:

>>> 
C:\Python27\lib\site-packages\pandas\core\strings.py:350: UserWarning: In future versions of pandas, match will change to always return a bool indexer.
" always return a bool indexer.""", UserWarning)
0 []
1 (C,)
2 []
3 []
4 []
5 []
Name: names, dtype: object
0 True
1 False
2 False
3 False
4 False
5 False
Name: names, dtype: bool

我测试了这两种模式,看看它是否是正则表达式,看起来可能是。

更新:确认这是一个正则表达式问题,更改了正则表达式并且工作正常。

df = pd.read_csv('patterntest.txt', header=None, dtype=str)
df.columns = ['names']
df['status']=''

patterns=['Cat', 'Dog']



for i in xrange(len(patterns)):
df.loc[df.names.str.match(patterns[i]),'status'] = 'CAPTURED'

那么有没有办法解决这个问题呢?

最佳答案

为了解释折旧(在 0.13 中)匹配的行为:它现在返回 bool 除非模式中有组(这里括号是组,因此 C 在一个中返回行)...:s

您应该使用str.contains而不是str.match *:

In [11]: s.str.contains('(?i)(C|H|L)at', flags=re.IGNORECASE)
Out[11]:
0 False
1 True
2 False
3 False
4 False
5 False
Name: name, dtype: bool

In [12]: s.str.contains('Dog', flags=re.IGNORECASE)
Out[12]:
0 True
1 False
2 False
3 False
4 False
5 False
Name: name, dtype: bool

要检查它是否是整个字符串,您应该使用开始 (^) 和结束 ($) 正则表达式:

In [13]: s.str.contains('^Dog$', flags=re.IGNORECASE)
Out[13]:
0 True
1 False
2 False
3 False
4 False
5 False
Name: name, dtype: bool

* 注意:match is deprecated 0.13。

关于Python IO 不可哈希列表正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21324135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com