我有一些代码可以用某些句子制作单字,双字和三字,但是我希望这段代码可以通过file.txt来制作,编程时的新手让我知道我必须做什么?
def ngrams(s, n=2, i=0):
while len(s[i:i+n]) == n:
yield s[i:i+n]
i += 1
txt ='Python is one of the awesomest languages'
unigram = ngrams(txt.split(), n=1)
a = list(unigram)
bigram = ngrams(txt.split(), n=2)
b = list(bigram)
trigram = ngrams(txt.split(), n=3)
c = list(trigram)
print('unigram:')
print(a)
print('bigram:')
print(b)
print('trigram:')
print(c)
答案 0 :(得分:0)
要写入文件时(请在open语句中注意“ w”):
with (open('some.txt', 'w')) as file:
file.write("this is an example!")
要读取文件时(请在open语句中注意“ r”):
with (open('some.txt', 'r')) as file:
line = file.readline();
print(line)
这对您来说应该是一个很好的起点。