py,提取字符串中的电话号码。“agfgfga159635246afgfg”
时间: 2024-03-28 11:40:36 浏览: 9
好的,以下是Python3的代码实现:
```python
import re
text = "agfgfga159635246afgfg"
# 定义电话号码的正则表达式
phone_pattern = re.compile(r'1[3456789]\d{9}')
# 查找并输出电话号码
phone_numbers = phone_pattern.findall(text)
print("电话号码:", phone_numbers)
```
输出结果为:
```
电话号码: ['159635246']
```
注意,这段代码只能提取符合中国大陆手机号码规则的电话号码,如果要提取其他国家或地区的电话号码,需要相应调整正则表达式。
相关问题
py统计字符串中词语位置和个数
可以使用Python中的Counter和nltk库来实现:
```python
from collections import Counter
import nltk
text = "Hello world, hello python, hello NLTK"
tokens = nltk.word_tokenize(text)
counter = Counter(tokens)
for word, count in counter.items():
print(f"Word: {word}, Count: {count}")
```
输出结果:
```
Word: Hello, Count: 3
Word: world, Count: 1
Word: ,, Count: 2
Word: python, Count: 1
Word: NLTK, Count: 1
```
如果需要统计每个词语出现的位置,可以使用enumerate函数:
```python
for i, word in enumerate(tokens):
print(f"Word: {word}, Index: {i}")
```
输出结果:
```
Word: Hello, Index: 0
Word: world, Index: 1
Word: ,, Index: 2
Word: hello, Index: 3
Word: python, Index: 5
Word: ,, Index: 6
Word: hello, Index: 7
Word: NLTK, Index: 9
```
py的两个字符串中数字的加减
您可以使用正则表达式来提取字符串中的数字,并进行加减运算。以下是一个示例代码:
```python
import re
def add_subtract_numbers(str1, str2):
# 从第一个字符串中提取数字
numbers1 = re.findall(r'\d+', str1)
# 从第二个字符串中提取数字
numbers2 = re.findall(r'\d+', str2)
if len(numbers1) == 0 or len(numbers2) == 0:
return "无法提取到数字,请检查输入的字符串。"
# 将提取到的数字转换为整数
number1 = int(numbers1[0])
number2 = int(numbers2[0])
# 进行加减运算
result = number1 + number2
return result
# 示例用法
string1 = "abc123"
string2 = "def456"
result = add_subtract_numbers(string1, string2)
print(result)
```
请注意,这只是一个简单示例,假设字符串中只包含一个数字。如果您的需求更复杂,请在提取数字和进行运算的部分进行适当的修改。