[英]How do I get my code to show a certain number of characters from a text file
In my assignment i'm expected to look for a word and only return a set number of characters (which is 80, and 40 on each side surrounding the word), without the use of nltk or regex. 在我的作业中,我希望找到一个单词并且只返回一定数量的字符(在单词的每一边是80和40),而不使用nltk或正则表达式。
I've set my code up as so 我已经设置了我的代码
open = open("a2.txt", 'r')
file2read = open.readlines()
name = 'word'
for line in file2read:
s2 = line.split ("\n", 1)
if name in line:
i = line.find(name)
half = (80 - len(name) - 2) // 2
left = line[i - half]
right = line[i + len(word) + half]
print(left + word + right)
but then my print out looks like this (updated screenshot) instead of the 80 character lines which i'm hoping to find. 但后来我的打印出来就像这样 (更新截图),而不是我希望找到的80个字符行。
Sorry if this is a really newbie error as i'm only 3 weeks into the program and i've been searching and can't seem to get the answer 对不起,如果这是一个真正的新手错误,因为我只有3周的程序,我一直在搜索,似乎无法得到答案
Instead of doing readlines which might not be consistent due to differences in windows/Unix you can also read the entire text at once: 由于Windows / Unix的差异,您可以同时读取整个文本,而不是执行可能不一致的readlines:
You don't need to separate it in lines: 您不需要按行分隔它:
with open('a2.txt', 'r') as file:
a = file.read()
name = 'word'
if name in a:
i = a.find(name)
half = (80 - len(name) - 2) // 2
left = a[i-half:i]
right = a[i+len(name):i + len(name) + half]
print(left + name + right)
This way you are reading the entire text at once. 这样您就可以立即阅读整个文本。 Finding your word and printing the necessary 80 characters. 找到你的单词并打印必要的80个字符。 This is the output 这是输出
ut. even know say trip tip sandwich. words describe it. meat eater, love it. b
If you want to make it work for all the words in the text. 如果你想让它适用于文本中的所有单词。 You will need to make a loop =) but that i'm sure you can figure it out by yourself! 你需要做一个循环=)但我相信你可以自己解决它!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.