删除少于4个字符的单词(python)

2024-04-26 05:05:33 发布

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

with open('text.txt','r') as f:
    for i in f:
        trantab = str.maketrans({key: None for key in string.punctuation})
        j = i.translate(trantab)
        result1.append(j)
shortword = re.compile(r'\W*\b\w{1,4}\b')
shortword.sub('', result1)
f = result1

错误是:

  line 13, in shortword.sub('', result1)
TypeError: expected string or bytes-like object

我该怎么修?你知道吗


Tags: keytextintxtnoneforstringas
2条回答

假设每个单词都在一行中,如果不是这样,就必须用.split()分解content

with open('something.txt') as f:
    content = [line.strip() for line in f]

res = list(filter(lambda x: len(x) >= 4, content))

出现此错误是因为您正在尝试[].sub()数组。。。你知道吗

我用这个脚本解决了你需要的问题:

import re

t = []
t.append("THIS IS A SIMPLE DUMMY TEXT")
t.append("ANOTHER INDEX BLA BLA")

for i in t: 
    shortword = re.compile(r'\W*\b\w{1,4}\b')
    t = shortword.sub('', str(t))

print(t)

你只需要分配短词.sub('',result1)到result1并确保使用str():

result1 = shortword.sub('', str(result1))

我相信那会对你有好处的!你知道吗

相关问题 更多 >