英文:
Why i'm facing Regex detection problem inside a loop in Python
问题
我在使用正则表达式时遇到了非常奇怪的问题。
```python
weight = 'abcd'
description = 'ml'
for symbol in Syntax['symbol']:
print(symbol)
weight = re.findall(symbol, description)
print(weight)
输出 --> []
Syntax是一个数据框,其中包含不同的单位,还包含在symbol列中的***"ml",我已经手动打印了symbol变量,它打印出所需的单位"ml"***,它将在循环中设置为模式,但仍然返回[]或None,使用re.match()时。但是,当我尝试下面的代码时
description = 'ml'
pattern = 'ml'
print(re.findall(pattern, description))
它打印出***"ml"***,为什么?上面和上面的代码在逻辑上是相同的。
[![在此输入图片描述][1]][1]
<details>
<summary>英文:</summary>
I'm facing very weird problem while using regex.
weight='abcd'
description='ml'
for symbol in Syntax['symbol']:
print(symbol)
weight=re.findall(symbol,description)
print(weight)
output --> []
***Syntax is a data frame*** that contains different units, also contains ***" ml "*** inside symbol column, i have manually printed the symbol variable it prints required unit that is ***"ml"*** which will be set as pattern in loop but still it returns [] OR None while using re.match().
But when i try code below
description='ml'
pattern='ml'
print(re.findall(pattern,description)
it prints ***"ml"***, Why ??? Both above and Top code are logically same.
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/yN84A.png
</details>
# 答案1
**得分**: 1
在顶部的代码中,由于`print(weight)`位于循环外部,所以您只打印了最终正则表达式搜索的结果。如果“ml”在您的数据框中的某个地方,那就很好,但如果`symbol`的*最后一个*值与`description`中的任何内容都不匹配,那么正则表达式将找不到任何匹配项,您将不会得到任何输出。
尝试在`for`循环内部打印`weight`,看看您会得到什么输出。
<details>
<summary>英文:</summary>
In the top code, you're only printing the result of the final regex search, since `print(weight)` is outside your loop. It's all well and good if "ml" is somewhere in your data frame, but if the *last* value of `symbol` doesn't match anything in `description`, the regex won't find any matches and you won't get any output.
Try printing `weight` inside the `for` loop and see what output you get.
</details>
# 答案2
**得分**: 0
description='ml'
weight=0
for symbol in self.units['symbol']:
print("units in Syntax dataframe : ", symbol)
weight=re.findall(symbol, description)
if weight!=[]:
break
print(weight)
<details>
<summary>英文:</summary>
description='ml'
weight=0
for symbol in self.units['symbol']:
print("units in Syntax dataframe : ",symbol)
weight=re.findall(symbol,description)
if weight!=[]:
break
print(weight)
I have understood the problem, i was not stopping the loop when the 'ml' is found, that's why it was printing [] or None
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论