2014-04-15 41 views
-1

我在Python中編程,但現在我想在Java中執行相同的代碼。你能幫我嗎?這是我在在文本文件中搜索字符串

import random 
import re 

a = "y" 

while a == "y": 
i = input('Search: ') 
b = i.lower() 
word2 = "" 
for letter in b: 
    lista = [] 
    with open('d:\lista.txt', 'r') as inF: 
    for item in inF: 
    if item.startswith(letter): 
     lista.append(item) 
    word = random.choice(lista) 
    word2 = word2 + word 

print(word2) 

a = input("Again? ") 

工作現在我想這樣做Java的,但林真的不知道如何做到這一點的代碼。它不是那麼容易。我只是一個初學者。到目前爲止,我創建了一個代碼,使得在文本文件中搜索,但我卡住了。

這是java代碼。它找到這個詞的位置。我一直在試圖修改它而沒有我期待的結果。

import java.io.*; 
import java.util.Scanner; 
class test { 

public static void main(String[] args){ 

    Scanner input = new Scanner(System.in); 
    System.out.println("Search: "); 
    String searchText = input.nextLine(); 
    String fileName = "lista.txt"; 
    StringBuilder sb = new StringBuilder(); 

    try { 

     BufferedReader reader = new BufferedReader(new FileReader(fileName)); 


     while (reader.ready()) { 

      sb.append(reader.readLine()); 
     } 

    } 
    catch(IOException ex) { 
     ex.printStackTrace(); 
    } 

    String fileText = sb.toString(); 
    System.out.println("Position in file : " + fileText.indexOf(searchText)); 

} 
} 

我希望的是找到一個文本文件,列表中的內容,但只是想表明,我想搜索的字符串的字母開頭的項目。例如,我有字符串「緊急」和文本文件包含: 寶寶 雷德曼 愛 城市 紳士 遊戲 大象 晚上 託德 所以顯示會「城市」 +「雷德曼」 +「紳士「+直到達到字符串的末尾。

+2

安置自己的Java代碼,到目前爲止,以及問題特別是。 – RossC

+1

您的Java代碼正在爲我工​​作,那麼問題是什麼?如果你只是告訴我你想要什麼,我可以給你一個答案。 – CodeCamper

回答

1

假設您已經對字符串進行了標記,以便您有一個字符串列表,每個字符串都包含一個單詞。如果你每行有一個單詞,這就是你的Python代碼的編寫方式。現在

String[] haystack = {"baby", "redman", "love", "urban", "gentleman", "game", 
    "elephant", "night", "todd"}; 

,尋找一根針,你可以簡單的草垛的第一個字符比較針的所有字符:

String needle = "urgent"; 

for (String s : haystack) { 
    for (int i = 0; i < needle.length(); ++i) { 
     if (s.charAt(0) == needle.charAt(i)) { 
      System.out.println(s); 
      break; 
     } 
    } 
} 

該解決方案運行在O(|針| * |草垛|)。 爲了提高它一下了額外的內存一點點的成本,我們可以預先計算的哈希表可用的啓動:

String needle = "urgent"; 
Set<Character> lookup = new HashSet<Character>(); 

for (int i = 0; i < needle.length(); ++i) { 
     lookup.add(needle.charAt(i));   
} 

for (String s : haystack) { 
    if (lookup.contains(s.charAt(0))) { 
     System.out.println(s); 
    } 
} 

第二種解決方案運行在O(|針| + |草堆|) 。

0

如果您的單詞列表不太大,則可以使用。如果你的單詞列表很大,你可以調整它,這樣你就可以多次收集文件並使用文件。

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileReader; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
import java.util.Random; 


public class Test { 

    public static void main(String[] args) { 
     Map<Character, List<String>> map = new HashMap<Character, List<String>>(); 
     File file = new File("./lista.txt"); 
     BufferedReader reader = null; 
     try { 
      reader = new BufferedReader(new FileReader(file)); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       // assumes words are space separated with no 
       // quotes or commas 
       String[] tokens = line.split(" "); 

       for(String word : tokens) { 
        if(word.length() == 0) continue; 

        // might as well avoid case issues 
        word = word.toLowerCase(); 

        Character firstLetter = Character.valueOf(word.charAt(0)); 

        List<String> wordsThatStartWith = map.get(firstLetter); 
        if(wordsThatStartWith == null) { 
         wordsThatStartWith = new ArrayList<String>(); 
         map.put(firstLetter, wordsThatStartWith); 
        } 

        wordsThatStartWith.add(word); 
       } 

      } 

      Random rand = new Random(); 
      String test = "urgent"; 

      List<String> words = new ArrayList<String>(); 
      for (int i = 0; i < test.length(); i++) { 
       Character key = Character.valueOf(test.charAt(i)); 
       List<String> wordsThatStartWith = map.get(key); 
       if(wordsThatStartWith != null){ 
        String randomWord = wordsThatStartWith.get(rand.nextInt(wordsThatStartWith.size())); 
        words.add(randomWord); 
       } else { 
        // text file didn't contain any words that start 
        // with this letter, need to handle 
       } 
      } 

      for(String w : words) { 
       System.out.println(w); 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      if(reader != null) { 
       try { 
        reader.close(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 
} 

這是假設lista.txt的內容看起來像

baby redman love urban gentleman game elephant night todd 

和輸出看起來像

urban 
redman 
gentleman 
elephant 
night 
todd