Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有人能帮我在Python中使用re.sub从字符串中删除数字数据吗?_Python_Re - Fatal编程技术网

有人能帮我在Python中使用re.sub从字符串中删除数字数据吗?

有人能帮我在Python中使用re.sub从字符串中删除数字数据吗?,python,re,Python,Re,我正在处理文本文件,数据如下。我只想从数据中删除1和0.6271之类的内容,而不是T123 page_data=1 0.6271 bacs T123 Biologically Active Substance page_data =re.sub(r"", ' ',page_data) 所需输出: bacs T123 Biologically Active Substance 正如评论所指出的,使用re可能会使事情变得过于复杂,在这里不太必要。如果不需要使用re,对于类似

我正在处理文本文件,数据如下。我只想从数据中删除1和0.6271之类的内容,而不是T123

page_data=1 0.6271 bacs T123 Biologically Active Substance
page_data =re.sub(r"", '  ',page_data)
所需输出:

bacs T123 Biologically Active Substance

正如评论所指出的,使用
re
可能会使事情变得过于复杂,在这里不太必要。如果不需要使用
re
,对于类似的情况,您可以执行一个简单的
try except
语句

def removenumeric(string):
    newstr = []
    for word in string.split():
        try:
            float(word)
        except ValueError:
            newstr.append(word)
    return ' '.join(newstr)
输出:

bacs T123 Biologically Active Substance

不能在此处使用
.isnumeric()
,因为对于浮点字符串,它将返回false。这就是为什么必须使用
float(word)
来创建准确的输出。

我阅读了@gmdev答案,但也想指出正则表达式的答案,以防正则表达式需要

正则表达式(仅匹配字符串中的浮点和整数):

使用此正则表达式排除匹配的部分(整数和浮点):

(^|\s)([-+]?\d*\.\d+\d+

Python用法:

import re

re.sub("(^|\s)([-+]?\d*\.\d+|\d+)", '', "1 0.6271 bacs T123 Biologically Active Substance")
输入:1 0.6271 bacs T123生物活性物质


输出:bacs T123生物活性物质

为什么您希望您的正则表达式(一个空字符串…)工作?你为什么坚持使用
re
?像
'.join(page_data.split()[2:])这样的东西有什么问题?甚至
page\u data.split(“”,2)[-1]
感谢您为我的场景所做的工作。上帝保佑你。再次感谢