连接文本中的单个字符

2024-06-16 09:29:49 发布

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

我有一份公司名称的清单,有些有缩写。例如:

compNames = ['Costa Limited', 'D B M LTD']

我需要使用以下方法将文本的compNames转换为令牌计数矩阵。但这不会为D B M LTD中的B D M输出列

count_vect = CountVectorizer(analyzer='word')
count_vect.fit_transform(compNames).toarray()

连接文本中单个字符的最佳方法是什么?你知道吗

ex: 'D B M LTD' to 'DBM LTD'

Tags: 方法文本名称count公司矩阵analyzerword
3条回答

下面是一个简短的函数,它将空格字符上的字符串分解为一个列表,迭代该列表,如果元素的长度为1,则生成一个临时字符串,当遇到长度大于1的元素时,将临时字符串追加到一个新列表。你知道吗

import re

a = 'D B M LTD'

def single_concat(s):
    out = []
    tmp = ''
    for x in re.split(r'\s+', s):
        if len(x) == 1:
            tmp += x
        else:
            if tmp:
                out.append(tmp)
            out.append(x)
            tmp = ''
    return ' '.join(out)

single_concat(a)
# returns:
'DBM LTD'
import re

s = "D B M LTD"

first_part = ''
for chunk in re.compile("([A-Z]{1})\s").split(s):
    if len(chunk) == 1:
        first_part += chunk
    elif len(chunk) > 1:
        last_part = chunk

print(first_part + " " + last_part)

打印DBM LTD。你知道吗

import re
string = 'D B M LTD'
print re.sub("([^ ]) ", r"\1", re.sub(" ([^ ]{2,})", r"  \1", string))

很尴尬,但应该有用。它在LTD前面增加了一个空间,然后用“D”替换“D”,用“B”替换“B”,依此类推。你知道吗

相关问题 更多 >