将文本中的逗号替换为十进制数字 (python) 的句点?

Replacing commas with periods in text for decimal numbers (python)?

  1. 我有一个数据集,它的字段包含文本信息(既有文字数据也有数字数据)。正如您在屏幕截图中看到的,有十进制数字。它们之间用逗号分隔,我需要确保它们之间有句点。

我之前曾尝试编写一个正则表达式,但它用句点替换了文本中的所有逗号。

Data_preprocessing['tweet_without_stopwords'] = Data_preprocessing['tweet_without_stopwords'].apply(lambda x: re.sub(",",'.', str(x)))

如何编写正则表达式,使其仅适用于数字的十进制表示法?也就是说,我想在文本中表达一个形式:number,number 文本中是这样的number.number

  1. 例子打破了数据
Data_preprocessing['tweet_without_stopwords'] = Data_preprocessing['tweet_without_stopwords'].apply(lambda x: re.sub("(\d*)\.(\d*)",",", str(x)))

方块出现了:D

3.

Data_preprocessing['tweet_without_stopwords'] = Data_preprocessing['tweet_without_stopwords'].apply(lambda x: re.sub("(\d+)\,(\d+)",".", str(x)))

结果再次

您需要的正则表达式是 "(\d+),(\d+)""."。分解:

(\d+)       at least one digit (group 1)
,           a literal ,
(\d+)       at least one digit (group 2)

替换

         group 1
.          a period
         group 2

应用于您的代码,相关部分将是

lambda x: re.sub(r"(\d+),(\d+)",r".", str(x))

Here's a testbed that verifies this regex is correct