如何实现读取data.txt生成数组并拆分超6字符的单词?
解决方案
首先,你需要调整读取文件后的处理逻辑,先将文本分割为独立单词,再针对长单词进行拆分。以下是修改后的完整脚本:
from datetime import datetime import time word2 = "" while True: now = datetime.now() current_time = now.strftime("%H:%M") hour = now.hour if 9 < hour < 23: if (now.minute == 4 or now.minute == 30) and now.second == 0: time.sleep(0.5) print(current_time) else: time.sleep(0.5) # 安全读取文件(用with语句自动关闭) with open('.\\data.txt', "r") as info: word1 = info.read().strip() if word1 != word2: backuptime = current_time processed_words = [] # 分割文本为单词 words = word1.split() for word in words: # 拆分长单词为不超过6字符的片段 for i in range(0, len(word), 6): processed_words.append(word[i:i+6]) # 输出处理后的片段 for segment in processed_words: print(segment) time.sleep(1) word2 = word1 time.sleep(8) print(backuptime)
关键修改点:
- 使用
split()将读取到的文本分割为独立单词,解决原脚本直接拆分整段文本的问题。 - 对每个单词循环拆分,每次截取6个字符(
range(0, len(word), 6)控制步长),确保片段长度不超过6。 - 改用
with语句读取文件,避免手动关闭文件时可能出现的资源泄漏问题。 - 简化了时间变量的获取,直接从
now对象中提取,减少重复调用datetime.now()。
测试示例:如果data.txt内容为"welcome home",处理后的processed_words数组就是["welcom","e","home"],符合你的需求。
内容的提问来源于stack exchange,提问作者ANT936
相关产品推荐
相关产品推荐

