替换字符串中的特定字符

2024-10-01 02:37:57 发布

您现在位置:Python中文网/ 问答频道 /正文

这可能是非常基本的,但我一直在努力。你知道吗

我有点像:

one = ['L', 'K', 'M']

two = ['P', 'N', 'S']

我还有一个字符串,比如说“看着我”,我想把它转换成“PooN at Se”。我的想法是循环遍历字符串的每个字母,循环遍历第一个列表,比较两个,如果它们是匹配的,只需将字符串中匹配的字母替换为列表一中的某个字母,再替换为列表二中的某个字母。你知道吗

循环被证明是非常低效的,因为我正在处理大文本。你知道吗

我访问的字符串实际上是数据帧中的行:

data = pd.read_csv('train.txt', delimiter='\t', header=None, names=['category', 'text'], dtype=str)

print data.head()给出了如下结果:

0 MUSIC Today at the recording studio, John... 1 POLITICS The tensions inside the government have... 2 NEWS The new pictures of NASA show...

我把课文分开

text = data['text']

这里的诀窍是,我实际上是在处理用西里尔文写的文本,我不能使用任何函数来降低大写字母,这是我的目标。我遇到的最好的问题是我在顶部介绍的问题,简单地定位每个大写字母并用它的小写等效字母替换它。你知道吗

有什么建议吗?你知道吗


Tags: the字符串text文本证明列表data字母
3条回答

似乎你需要^{}

print (data)
                                                text
0         MUSIC  Today at the recording studio, John
1  POLITICS  The tensions inside the government have
2                NEWS  The new pictures of NASA show

one = ['L', 'K', 'M']
two = ['P', 'N', 'S']
data['text'] = data['text'].replace(one, two, regex=True)
print (data)
                                                text
0         SUSIC  Today at the recording studio, John
1  POPITICS  The tensions inside the government have
2                NEWS  The new pictures of NASA show
#use list comprehension
''.join([e if e not in one else two[one.index(e)] for i,e in enumerate(s)])
Out[523]: 'PooN at Se'

您可以创建一个转换表,并使用translate方法。你知道吗

translation_table = str.maketrans("ABÉПЯ", "abéпя")

text = "Éléphant Язы́к"

text.translate(translation_table)
# 'éléphant язы́к'

我们使用maketrans来创建翻译表。我们用它来表示参数,两个长度相等的字符串。 然后我们使用字符串的translate方法。你知道吗

相关问题 更多 >