在Python中,删除文件中的数字可以通过多种方法实现,以下是几种常见的方法:
1. 使用正则表达式:
```python
import re
filename = "file123.txt"
new_filename = re.sub(r'\d', '', filename)
print(new_filename) 输出:file.txt
2. 使用列表推导式:
```python
string = "abcd1234efg567"
newstring = ''.join([i for i in string if not i.isdigit()])
print(newstring) 输出:abcdefgh
3. 使用`str.translate()`方法:
```python
text = "hello123world"
translator = str.maketrans('', '', string.digits)
text_without_digits = text.translate(translator)
print(text_without_digits) 输出:helloworld
4. 使用`str.extract()`方法:
```python
df['a'].str.extract(r'([\d.])(\w+)') 提取数字和非数字部分
5. 从文本文件中删除每行最前的数字:
```python
with open('new.txt', 'w', encoding='utf-8') as file_object:
for line in fileinput.input('file.txt', inplace=True):
if line.isdigit():
continue
file_object.write(line)
6. 使用`fileinput`模块删除数字和点:
```python
import fileinput
for line in fileinput.input('/content/drive/MyDrive/0.txt', inplace=True):
删除数字和点
line = re.sub(r'\d|\.', '', line)
print(line, end='')
选择适合你需求的方法,可以轻松地从文本或文件中删除数字