0

到目前为止,我得到了这个...

with open('d:\word_list.txt', 'r') as inF: 
b = input('Enter word: ') 
for letter in b: 
 for item in inF: 
  if item.startswith(letter): 
   print(item) 

如果我输入“zucaritas”,这段代码只打印那些以“z”开头的单词,而不是其他字母,“u”,“c”等。我想检查列表中以每个开头的所有单词我想输入的字母。我能做些什么?顺便说一句,我是python的初学者。谢谢

4

3 回答 3

2

第一次迭代inF会耗尽它,并且不能再次迭代。所以循环只会对b.

您可以通过重复打开文件来获得一个新的文件对象,对于每个字母b

b = input('Enter word: ') 
for letter in b: 
 with open('d:\word_list.txt', 'r') as inF: 
  for item in inF: 
   if item.startswith(letter): 
    print(item) 

或者,您可以使用以下命令手动将文件对象倒回到其开始状态seek

with open('d:\word_list.txt', 'r') as inF: 
 b = input('Enter word: ') 
 for letter in b: 
  inF.seek(0)
  for item in inF: 
   if item.startswith(letter): 
    print(item) 
于 2013-09-27T13:24:46.397 回答
0

您可以通过文件中的单词列表一次打印所有以给定单词中的任何字母开头的单词:

#!/usr/bin/env python3
letters = tuple(input('Enter word: ')) # startswith() can work with a tuple
with open(r'd:\word_list.txt') as file:
    for word in file:
        if word.startswith(letters): # if word starts with any of the letters
           print(word, end='')
于 2014-10-22T06:20:29.983 回答
0

节点 JS 脚本

var fs = require("fs");
var letter = process.argv[2];

var writeStream = fs.createWriteStream("./letters/" + letter + ".txt");


fs.createReadStream("./word_list.txt").on("data", function(chunk){
    var words = chunk.toString().split("\n");
    words.forEach(function(word){
        var firstLetter = word.charAt(0);
        if(firstLetter == letter || firstLetter == letter.toUpperCase()){
            console.log(firstLetter);
            writeStream.write(word + "\n");
            console.log("wrote " + word);
        }else{

        }



    });
});

你可以这样称呼它node your_script_name.js b以将所有以开头的单词保存b到一个名为的文件中letters/b.txt

于 2014-10-21T20:26:05.273 回答