python - 从 txt 文件一次打印 10 个单词
问题描述
我正在尝试打印 txt 文件中的前 10 个单词,然后是接下来的 10 个单词,然后是下一个……
这是我目前拥有的
text_file= open("read_it.txt", "r")
lines= text_file.readlines()
lineNum= 0
words= lines[lineNum].split()
wordNum= 0
text_file.close()
def printWords():
global wordNum
global lineNum
global words
lineNum= lineNum+1
words= lines[lineNum].split()
wordNum= 0
print(words[wordNum])
wordNum=wordNum+1
print(words[wordNum])
wordNum=wordNum+1
但是如果我这样做的话,我必须有这两条线 10 次我想知道是否有更有效的方法来做到这一点
解决方案
我建议您使用正则表达式并拆分为单词,而不是按行拆分并将行拆分为单词。我会做的就是这样
# Get list of words from file "word_filename", default to "test.txt"
def get_words(word_filename='test.txt'):
# Regular expression library for re.split
import re
# Open the text file
with open(word_filename, 'r') as file:
# Generate the word list (Split with non-word as delimiter)
yield from re.split(r'\W+', file.read())
# Get a list of "limit" words, default to 10
def get_n_words(limit=10):
# Initialize the word list to store 10 words
words = []
# Loop through all the words
for word in get_words():
# Skip empty word
if len(word) == 0: continue
# Check if the word list have "limit" number of words
if len(words) == limit:
# Returns the word list
yield words
# Reset the word list
words = []
# The word list does not have enough size of "limit"
else:
# Insert the word
words.append(word)
# Check the remaining word list in case it doesn't have size of "limit"
if len(words) > 0: yield words
# Loop through the 10 word lists
for ten_words in get_n_words():
# Print the 10 words comma separated
print(', '.join(ten_words))
推荐阅读
- javascript - 在单独的窗口中渲染 Monaco 编辑器
- python - 提交表单而不刷新页面
- php - 如何从复杂的 php 对象中获取特定变量?
- reactjs - 如何在 React JS 中加载 SVG 列表
- python - 如何将opencv中处理的帧发送到另一个本地系统
- swift - UIDatePicker 倒计时计时器模式在 Xcode 10.3 中不返回正确的时间
- php - 在while循环中输入PHP
- ormlite-servicestack - 连接表列上的 ServiceStack OrmLite OrderBy
- c# - 修补子实体的属性。如何正确映射实体以执行补丁方法
- android - 制作 OpenCV 源代码。错误日志:/bin/sh:./gradlew:没有这样的文件或目录