我想用逗号‘,’,句号‘’和空格‘’,不使用任何内置的拆分函数,并将这些单词追加到列表中.

输入: 嗨,欢迎来到MK培训.我喜欢Python .

预期输出: [‘嗨’,‘欢迎’,‘来’,‘MK’,‘培训’,‘我’,‘爱’,‘Python ’]

以下是我try 过的代码:

s = "Hi, Welcome to MK training. I love python."
c_pos = -1
last_pos = - 1
r = []
for i in s[c_pos+1:]:
  if i == ' ' or i == ',' or i == '.':
      c_pos = s.index(i, c_pos+1)
      r.append(s[last_pos+1:c_pos])
      last_pos = c_pos

print(r)

输出: [‘嗨’,‘’,‘欢迎’,‘to’,‘MK’,‘培训’,‘’,‘我’,‘爱’,‘Python ’]

我知道如果我使用List Remove()方法,我可以从List中删除‘’,并且我会得到我预期的输出.我想要的是,做所有的操作与字符串和拆分逗号,句号和空格从字符串不使用任何拆分函数,并附加在一个列表中的这些单词.我不想对List做任何事情.

推荐答案

您可以try 这样的操作:

data = 'Hi, Welcome to MK training. I love python.'

words = []
word = ''

# loop through each character
for x in data:

    print('Processing ' + x)

    # if character is a separator and if word variable has something in it
    # then store it in words list
    if x in [',', '.', ' ']:
        
        print('!! Found a separator !!')

        if word:
            print(f'Adding the word "{word}" to {words}. Resetting word.')
            words.append(word)
            word = ''
            print(f'Words is now {words}')

    else:
        word += x
        print(f'Word is {word}')

# after looping through all characters, if there's still something
# in word, store it in words list
if word:
    words.append(word)

print(words)

示例:https://www.ideone.com/DYPsem

Explanation

如果输入的是"Hello,There",我们将遍历每个字符.

  • 我们判断该字符是否为分隔符.H并非如此.因此,我们将其存储在Word中
  • 我们判断e,它不是分隔符.所以,我们把它加在H后面,使他
  • 我们判断了L,我们的话就变成了地狱
  • 我们对第二个也是这样做的.我们的话现在是地狱
  • 我们对o这样做.我们现在的单词是Hello
  • 然后我们就到了,岁.那是一个分隔符.所以,我们问:世界上有什么东西吗?是!这就是哈罗
  • 太棒了!我们将Hello添加到单词列表中,单词将变为[‘Hello’]
  • 我们继续到 ,这是一个分隔符.我们问:世界上有什么东西吗?不是的.这个词是空的.所以,什么都不要做.
  • 我们继续这样做,并循环访问所有角色

当您到达结尾时,如果没有分隔符,则Word将包含there.所以,我们最后一次问:Word中有什么东西吗?如果有的话,把它加到单词里.所以,单词变成了[‘Hello’,‘There’]

试一试吧.

Python-3.x相关问答推荐

Python多处理池:缺少一个进程

PythonPandas READ_EXCEL空数据帧

PANDAS中当前数据帧的匹配与更新

Python VS Code 自动导入路径包含 src

删除浮点型数据集中每列重复值比例超过一定阈值的列

aiogram机器人中处理文本输入异常而不是按钮点击的回调函数.

如何将日期时间索引写入日期类型的表?

将逗号分隔的字符串类型系列转换为整数列表 pandas

Python BeautifulSoup:在 Select 语句中排除其他标签

聚合(aggregate)为最多包含两个元素的列表

通过 requests 库调用 API 获取访问令牌

如何将具有多个参数的函数传递给 python concurrent.futures.ProcessPoolExecutor.map()?

UnicodeDecodeError:utf-8编解码器无法解码位置 1 的字节 0x8b:无效的起始字节,同时读取Pandas中的 csv 文件

Python:&= 运算符

使用 urllib3 忽略证书验证

没有名为urlparse的模块,但我没有使用 urlparse

带有数千个逗号刻度标签的 MatPlotLib 美元符号

有没有一种标准方法来确保 python 脚本将由 python2 而不是 python3 解释?

调用 Python doctest 时如何启用省略号?

有没有办法在多个线程中使用 asyncio.Queue ?