2014-04-15 7 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? ") 

작업 된 코드입니다. 그리 쉽지는 않습니다. 임 그냥 초보자. 지금까지 텍스트 파일에서 검색을 수행하는 코드를 만들었지 만 막혔습니다.

이것은 자바 코드입니다. 그것은 단어의 위치를 ​​찾습니다. 나는 찾고있는 결과없이 그것을 수정하려고 노력하고있다. 내가 원하는 무엇

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

포스트 자바 코드 같은 것을보고, 할 것이다 . – RossC

+1

Java 코드가 저에게 효과적이므로 문제가 무엇입니까? 니가 원하는 것을 나에게 말해 준다면 나는 대답을 줄 수있다. – CodeCamper

답변

1

문자열을 이미 토큰 화 했으므로 각각 하나의 단어가 들어있는 문자열 목록이 있다고 가정 해 봅시다. 한 줄에 하나의 단어가있는 경우 독자가 제공하는 것입니다. 이것이 바로 파이썬 코드가 작성된 방식입니다.

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