【问题标题】:How do I match a string exactly in python? [duplicate]如何在python中完全匹配一个字符串? [复制]
【发布时间】:2020-12-25 07:34:12
【问题描述】:

我有一个包含两个相似短语的数据框,例如“Hello World”和“Hello World 1”。我只想匹配“Hello World”字符串。

我目前正在使用: dataframe['Phrase'].str.match('Hello World') 但这显然会返回短语“Hello World”和“Hello World 1”。有没有办法只匹配短语?

【问题讨论】:

标签: python string match


【解决方案1】:

你只需要做一个相等性测试:

dataframe['Phrase'] == 'Hello World'

这将返回一个类似于您的子字符串匹配情况的布尔数组,但需要完全匹配。

示例:

a.csv

Phrase,Other_field
Hello World,1
Hello World 1,2
Something else,3

数据框:

>>> import pandas as pd
>>> dataframe = pd.read_csv('a.csv')

>>> dataframe
           Phrase  Other_field
0     Hello World            1
1   Hello World 1            2
2  Something else            3

你的子字符串匹配:

>>> dataframe['Phrase'].str.match('Hello World')
0     True
1     True
2    False
Name: Phrase, dtype: bool

完全匹配:

>>> dataframe['Phrase'] == 'Hello World'
0     True
1    False
2    False
Name: Phrase, dtype: bool

【讨论】:

    【解决方案2】:

    字符串上的正则表达式。

    import re
    
    ...
    ...
    
    if re.search(r'^Hello World$', data_frame_string):
        # Then the string matches, do whatever with the string.
        ....
        
    

    【讨论】:

      【解决方案3】:

      您可以使用 RegEx 获得这样的结果:

      import re
      
      phrase_to_find = 'Hello World'
      phrases = ['Hello World', 'Hello World 1']
      
      for phrase in phrases:
          if re.search(r'\b' + phrase + r'\b', phrase_to_find):
              print('Found the following match: {}'.format(phrase))
      

      \b 表示单词边界。

      【讨论】:

      • 嗨@Luke Wild,我的解决方案对您有用吗?如果是这样,请考虑投票和/或选择它作为答案。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2016-10-03
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多